<?php

namespace App\Models;

use App\Http\Controllers\Pc\TaskController;
use App\Libs\wrapper\Task;
use App\Models\Common\Constant;
use App\Models\InventoryModel;
use App\Models\ResourceModel\AmazonPlaceOrderDetailModel;
use App\Models\ResourceModel\AmazonPlaceOrderTaskModel;
use App\Models\ResourceModel\AmazonTeamTaskDetail;
use App\Models\ResourceModel\AmazonTeamTaskOne;
use App\Models\ResourceModel\AnokContractClothingModel;
use App\Models\ResourceModel\AnokEnquiriesModel;
use App\Models\ResourceModel\BaseSpuModel;
use App\Models\ResourceModel\TasksModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Controllers\Jobs\ExcelTaskController;
use App\Models\ResourceModel\SpuModel;

class Datawhole extends BaseModel
{
    const AMAZON_PLACE_ORDER_TASK_STATUS_NAME = [
        '-1' => '已撤销',
        '0' => '为发布任务',
        '1' => '已发布任务，待审核',
        '2' => '已审核，待录入艾诺科',
        '3' => '已录入艾诺科',
        '4' => '艾诺科下单审批通过'
    ];
    const FILTER_DATE = '2023-02-27 00:00:00';
    const COUNTRY = [
        'E' => '欧版',
        'U' => '美版'
    ];
    protected $amazonPlaceOrderTaskModel;
    protected $amazonPlaceOrderDetailModel;
    protected $taskModel;
    protected $spuModel;
    protected $bashSpuModel;
    protected $anokContractClothingModel;
    protected $anokEnquiriesModel;
    protected $amazonTeamTaskDetailModel;
    protected $amazonTeamTaskOneModel;
    public function __construct()
    {
        $this->amazonPlaceOrderTaskModel = new AmazonPlaceOrderTaskModel();
        $this->amazonPlaceOrderDetailModel = new AmazonPlaceOrderDetailModel();
        $this->taskModel = new TasksModel();
        $this->spuModel = new SpuModel();
        $this->bashSpuModel = new BaseSpuModel();
        $this->anokContractClothingModel = new AnokContractClothingModel();
        $this->anokEnquiriesModel = new AnokEnquiriesModel();
        $this->amazonTeamTaskDetailModel = new AmazonTeamTaskDetail();
        $this->amazonTeamTaskOneModel = new AmazonTeamTaskOne();
    }

    public function getCategoryId()
    {
        $sql = "select * from amazon_category";
        $shops = DB::select($sql);
        return $shops;
    }

    //获取数据统计与分析报表-总-更改字段方法
    //需要更改表结构
    //amazon_order_item 销量  category_id  user_id  spu      update amazon_order_item as a,amazon_skulist as l set a.category_id = l.category_id ,a.user_id = l.user_id , a.spu = l.spu where a.seller_sku = l.sku;
    //amazon_buhuo_detail 发货   category_id  spu  update amazon_buhuo_detail as a,amazon_skulist as l set a.category_id = l.category_id , a.spu = l.spu where a.sku = l.sku;
    //saihe_product_detail 库存  category_id  user_id shop_id  spu  update saihe_product_detail as a,amazon_skulist as l set a.category_id = l.category_id ,a.user_id = l.user_id , a.spu = l.spu where a.order_source_sku = l.sku;
    //product_detail 库存2   category_id  user_id  spu update product_detail as a,amazon_skulist as l set a.category_id = l.category_id ,a.user_id = l.user_id , a.spu = l.spu where a.sellersku = l.sku;

//    public function getDatawholeAll($params)
//    {
//
//        //获取库存
//        $Inventory = $this->getInventoryByOther($params);
//        //2个sql语句  0.1s  0.045s
//
//        //获取发货与销量
//        $Datawhole = $this->getDatawholeByOther($params);
//        //2个sql语句 0.031s 0.027s
//
//        $total = array_merge($Inventory, $Datawhole);
//        $total['category'] = '总计';
//
//        //根据分类
//        // if (!empty($params['category_id'])) {
//        //     $where .= " and category_id = {$params['category_id']}";
//        // }
//
//
//        $list = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku','=','sc.custom_sku')->leftjoin('self_spu as sp','sk.spu','=','sp.spu')->leftjoin('self_color_size as cz','sc.size','=','cz.identifying')->where('sk.goods_style','!=',0);
//
//        $listcount = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku','=','sc.custom_sku')->leftjoin('self_spu as sp','sk.spu','=','sp.spu')->where('sk.goods_style','!=',0);
//        // $where['sk.status'] = 1;
//        //大类
//        $params['two_cate_id']  = 17;
//        if (!empty($params['one_cate_id'])) {
//            $list= $list->where('sp.one_cate_id',$params['one_cate_id']);
//            $listcount =$listcount->where('sp.one_cate_id',$params['one_cate_id']);
//        }
//        //二类
//        if (!empty($params['two_cate_id'])) {
//            $list= $list->where('sp.two_cate_id',$params['two_cate_id']);
//            $listcount =$listcount->where('sp.two_cate_id',$params['two_cate_id']);
//        }
//
//        $count = $list->count();
//        $res = $list->get();
//
//        var_dump($count);
//        var_dump($res);
//        exit;
//        //三类
//        if (!empty($params['three_cate_id'])) {
//            $where['sp.three_cate_id'] = $params['three_cate_id'];
//        }
//        //根据店铺
//        if (!empty($params['shop_id'])) {
//            $where['sk.shop_id'] = $params['shop_id'];
//        }
//        //根据运营
//        if (!empty($params['user_id'])) {
//            $where['sk.user_id'] = $params['user_id'];
//        }
//        //根据spu
//        if (!empty($params['spu'])) {
//            $spu = $this->GetNewSpu($params['spu']);
//            if ($spu) {
//                $where['sk.spu'] = $spu;
//            }
//        }
//
//        //根据库存sku
//        if (!empty($params['custom_sku'])) {
//            $custom_sku = $this->GetNewCustomSku($params['custom_sku']);
//            if ($custom_sku) {
//                $where['sk.custom_sku'] = $custom_sku;
//            }
//        }
//
//        //根据sku
//        if (!empty($params['sku'])) {
//            $sku = $this->GetNewSku($params['sku']);
//            if ($sku) {
//                $where['sk.sku'] = $sku;
//            }
//        }
//
//        if (!empty($params['store'])) {
//            // $where['sk.shop_id']=$params['store'];
//            $list= $list->where('sk.shop_id',$params['store']);
//            $listcount =$listcount->where('sk.shop_id',$params['store']);
//        }
//
//        // $list = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc', 'sk.custom_sku', '=', 'sc.custom_sku')->leftjoin('self_spu as sp', 'sk.spu', '=', 'sp.spu')->where($where);
//        // //根据sku
//
//
//        // $list = $list->get();
//        if (isset($params['start_time'])) {
//            $start = $params['start_time'] . ' 00:00:00';
//        }
//        if (isset($params['end_time'])) {
//            $end = $params['end_time'] . ' 23:59:59';
//        }
//        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
//        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
//
//        $page = isset($params['page']) ? $params['page'] : 1;
//        $limit = isset($params['limit']) ? $params['limit'] : 30;
//        $page = $this->getLimitParam($page, $limit);
//
//        $limitsql = "LIMIT $page,$limit";
//
//        //获取sku
//        $sql = "select SQL_CALC_FOUND_ROWS sku,spu,user_id,shop_id,category_id,img,father_asin from amazon_skulist  where $where group by sku $limitsql";
//
//        $skus = DB::select($sql);
//        $totalNum = DB::select("SELECT FOUND_ROWS() as total")[0]->total;
//
//        //查询品类表所有品类数据拼接到$categoryName
//        $categorySql = "select `id`,`product_typename` from amazon_category";
//        $categoryData = DB::select($categorySql);
//        $categoryName = array();
//        if ($categoryData) {
//            foreach ($categoryData as $categoryVal) {
//                $categoryName[$categoryVal->id] = $categoryVal->product_typename;
//            }
//        };
//
//        //查询用户表拼接到$userName
//        $userSql = "select `id`,`account` from users";
//        $userData = DB::select($userSql);
//        $userName = array();
//        if ($userData) {
//            foreach ($userData as $userVal) {
//                $userName[$userVal->id] = $userVal->account;
//            }
//        };
//        //查询店铺表拼接到 $shopName
//        $shopSql = "select `id`,`shop_name` from shop where platform_id=5";
//        $shopData = DB::select($shopSql);
//        $shopName = array();
//        if ($shopData) {
//            foreach ($shopData as $shopVal) {
//                $shopName[$shopVal->id] = $shopVal->shop_name;
//            }
//        };
//
//
//        //查询spu生产下单表所有数据拼接到 $productionName
//        $productionSql = "select * from production_order";
//        $productionData = DB::select($productionSql);
//        $productionName = array();
//        if ($productionData) {
//            foreach ($productionData as $productionVal) {
//                $productionName[$productionVal->style_no]['order_num'] = $productionVal->order_num;
//                $productionName[$productionVal->style_no]['shipment_num'] = $productionVal->shipment_num;
//            }
//        };
//
//        //获取spu
//        $spusql = "select spu from amazon_skulist  where $where group by spu";
//
//        $spus = DB::select($spusql);
//        $order_num = 0;
//        $shipment_num = 0;
//        foreach ($spus as $spv) {
//            # code...
//            if (!empty($spv->spu)) {
//                foreach ($productionName as $pk => $pv) {
//                    if ($spv->spu == $pk) {
//                        $order_num += $productionName[$spv->spu]['order_num'];
//                        $shipment_num += $productionName[$spv->spu]['shipment_num'];
//                    }
//                }
//
//            }
//        }
//
//        $total['order_num'] = $order_num;
//        $total['shipment_num'] = $shipment_num;
//        $total['conversion_rate'] = 0;
//
//
//        $return_sum = 0;
//        foreach ($skus as $k => $uv) {
//
//            $params['sku'] = $uv->sku;
//            $res = $this->getDatawholeSkuDetail($params);
//            $res['in_warehouse_inventory'] = $res['in_warehouse_inventory'] ?? 0;
//            $uv->in_warehouse_inventory = (int)$res['in_warehouse_inventory'];
//            $res['reserved_inventory'] = $res['reserved_inventory'] ?? 0;
//            $uv->reserved_inventory = (int)$res['reserved_inventory'];
//            $res['tongAn_inventory'] = $res['tongAn_inventory'] ?? 0;
//            $uv->tongAn_inventory = (int)$res['tongAn_inventory'];
//            $res['in_road_inventory'] = $res['in_road_inventory'] ?? 0;
//            $uv->in_road_inventory = (int)$res['in_road_inventory'];
//            $res['quantity_ordered'] = $res['quantity_ordered'] ?? 0;
//            $uv->quantity_ordered = (int)$res['quantity_ordered'];
//            $res['courier_num'] = $res['courier_num'] ?? 0;
//            $uv->courier_num = (int)$res['courier_num'];
//            $res['shipping_num'] = $res['shipping_num'] ?? 0;
//            $uv->shipping_num = (int)$res['shipping_num'];
//            $res['air_num'] = $res['air_num'] ?? 0;
//            $uv->air_num = (int)$res['air_num'];
//
//
//            //转化率
//            $res['conversion_rate'] = 0;
//            $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where sku = '{$uv->sku}' and ds between '{$start_time}' and '{$end_time}'";
//            $percentage = Db::select($percentage_sql);
//            $session_percentage = $percentage[0]->session_percentage ?? 0;
//            $conversion_rate = 0;
//            if ($session_percentage > 0 && $res['quantity_ordered'] > 0) {
//                $quantity_ordered = $res['quantity_ordered'];
//                $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
//            }
//            $res['conversion_rate'] = (int)$conversion_rate;
//            $uv->conversion_rate = (int)$res['conversion_rate'];
//
//            $uv->account = $userName[$uv->user_id] ?? '';
//            $uv->shop_name = $shopName[$uv->shop_id] ?? '';
//            $uv->category = $categoryName[$uv->category_id] ?? '';
//            $uv->spu = $uv->spu ?? '';
//
//            $order_num = $productionName[$uv->spu]['order_num'] ?? 0;
//            $uv->order_num = (int)$order_num;
//            $shipment_num = $productionName[$uv->spu]['shipment_num'] ?? 0;
//            $uv->shipment_num = (int)$shipment_num;
//            //退货
//            $report_sql = "select sum(quantity) as return_num from amazon_report where sku = '{$uv->sku}' and return_date between '{$start_time}' and '{$end_time}'";
//            $report = Db::select($report_sql);
//            $skus[$k]->return_num = 0;
//            $skus[$k]->return_rate = 0;
//
//            $returnnum = empty($report[0]->return_num) ? 0 : $report[0]->return_num;
//            $skus[$k]->return_num = (int)$returnnum;
//            $return_sum += (int)$returnnum;
//            $return_rate = $res['quantity_ordered'] > 0 && !empty($report[0]->return_num) ? round($report[0]->return_num / $res['quantity_ordered'], 4) * 100 : 0;
//            $skus[$k]->return_rate = $return_rate;
//
//        }
//
//        $total['return_num'] = $return_sum;
//        $total['return_rate'] = empty($total['quantity_ordered']) ? 0 : round($total['return_num'] / $total['quantity_ordered'], 2) * 100 . '%';
//
//        return [
//            'total' => $total,
//            'data' => $skus,
//            'totalnum' => $totalNum,
//        ];
//    }


    //新品列表
//    public function getDatawholeNew($params)
//    {
//
//
//        $where = "1=1 and a.sku!=''";
//        //根据分类
//        if (!empty($params['category_id'])) {
//            $where .= " and a.category_id = {$params['category_id']}";
//        }
//        //根据店铺
//        if (!empty($params['shop_id'])) {
//            $where .= " and a.shop_id = {$params['shop_id']} ";
//        }
//        //根据运营
//        if (!empty($params['user_id'])) {
//            $where .= " and a.user_id = {$params['user_id']} ";
//        }
//        //根据spu
//        if (!empty($params['spu'])) {
//            $where .= " and a.spu = '{$params['spu']}' ";
//        }
//        //根据sku
//        if (!empty($params['sku'])) {
//            $where .= " and a.sku like '%{$params['sku']}%' ";
//        }
//
//        if (isset($params['start_time'])) {
//            $inventoryParams['start_time'] = $params['start_time'];
//            $start = $params['start_time'] . ' 00:00:00';
//        }
//        if (isset($params['end_time'])) {
//            $inventoryParams['end_time'] = $params['end_time'];
//            $end = $params['end_time'] . ' 23:59:59';
//        }
//
//        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
//        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
//
//        $page = isset($params['page']) ? $params['page'] : 1;
//        $limit = isset($params['limit']) ? $params['limit'] : 30;
//        $page = $this->getLimitParam($page, $limit);
//
//        $limitsql = "LIMIT $page,$limit";
//
//        $now = time() - 7776000;
//        $nowtime = date('Y-m-d H:i:s', $now);
//
//        //获取sku
//        $sql = "select SQL_CALC_FOUND_ROWS a.sku,a.spu,a.user_id,a.img,a.shop_id,a.category_id,MIN(b.operation_date) as min from amazon_skulist a left join  saihe_warehouse_log b on a.sku = b.sku where $where and b.type=2 group by sku  having min>'$nowtime' $limitsql ";
//
//
//        $skus = DB::select($sql);
//        $totalNum = DB::select("SELECT FOUND_ROWS() as total")[0]->total;
//
//        //查询品类表所有品类数据拼接到$categoryName
//        $categorySql = "select `id`,`product_typename` from amazon_category";
//        $categoryData = DB::select($categorySql);
//        $categoryName = array();
//        if ($categoryData) {
//            foreach ($categoryData as $categoryVal) {
//                $categoryName[$categoryVal->id] = $categoryVal->product_typename;
//            }
//        };
//
//        //查询用户表拼接到$userName
//        $userSql = "select `id`,`account` from users";
//        $userData = DB::select($userSql);
//        $userName = array();
//        if ($userData) {
//            foreach ($userData as $userVal) {
//                $userName[$userVal->id] = $userVal->account;
//            }
//        };
//        //查询店铺表拼接到 $shopName
//        $shopSql = "select `id`,`shop_name` from shop where platform_id=5";
//        $shopData = DB::select($shopSql);
//        $shopName = array();
//        if ($shopData) {
//            foreach ($shopData as $shopVal) {
//                $shopName[$shopVal->id] = $shopVal->shop_name;
//            }
//        };
//
//
//        //查询spu生产下单表所有数据拼接到 $productionName
//        $productionSql = "select * from production_order";
//        $productionData = DB::select($productionSql);
//        $productionName = array();
//        if ($productionData) {
//            foreach ($productionData as $productionVal) {
//                $productionName[$productionVal->style_no]['order_num'] = $productionVal->order_num;
//                $productionName[$productionVal->style_no]['shipment_num'] = $productionVal->shipment_num;
//            }
//        };
//
//
//        foreach ($skus as $uv) {
//
//
//            $report_sql = "select sku,sum(quantity) as return_num from amazon_report where sku = '{$uv->sku}' and return_date between '{$start_time}' and '{$end_time}' ";
//            $report = Db::select($report_sql);
//
//            $params['sku'] = $uv->sku;
//            $res = $this->getDatawholeSkuDetail($params);
//            $uv->in_warehouse_inventory = $res['in_warehouse_inventory'] ?? 0;
//            $uv->reserved_inventory = $res['reserved_inventory'] ?? 0;
//            $uv->tongAn_inventory = $res['tongAn_inventory'] ?? 0;
//            $uv->in_road_inventory = $res['in_road_inventory'] ?? 0;
//            $uv->quantity_ordered = $res['quantity_ordered'] ?? 0;
//            $uv->courier_num = $res['courier_num'] ?? 0;
//            $uv->shipping_num = $res['shipping_num'] ?? 0;
//            $uv->air_num = $res['air_num'] ?? 0;
//
//            $uv->return_num = $report[0]->return_num ?? 0;
//            $uv->return_rate = $uv->quantity_ordered > 0 ? round($uv->return_num / $uv->quantity_ordered, 4) * 100 : 0;
//            //转化率
//            $conversion_rate = 0;
//            $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where sku = '{$uv->sku}' and ds between '{$start_time}' and '{$end_time}'";
//            $percentage = Db::select($percentage_sql);
//            $session_percentage = $percentage[0]->session_percentage ?? 0;
//            $uv->session_percentage = $session_percentage ?? 0;
//            $conversion_rate = 0;
//            if ($session_percentage > 0 && $res['quantity_ordered'] > 0) {
//                $quantity_ordered = $res['quantity_ordered'];
//                $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
//            }
//            $uv->conversion_rate = (int)$conversion_rate;
//
//
//            $uv->account = $userName[$uv->user_id] ?? '';
//            $uv->shop_name = $shopName[$uv->shop_id] ?? '';
//            $uv->category = $categoryName[$uv->category_id] ?? '';
//            $uv->spu = $uv->spu ?? '';
//
//            $uv->order_num = $productionName[$uv->spu]['order_num'] ?? 0;
//            $uv->shipment_num = $productionName[$uv->spu]['shipment_num'] ?? 0;
//
//
//            //出入库时间
//            //出
//            $outSql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where sku='{$uv->sku}' and type =1 order by max desc limit 1 ";
//            $outData = DB::select($outSql);
//            //入
//            $insql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where sku='{$uv->sku}' and type =2 order by max desc limit 1 ";
//            $inData = DB::select($insql);
//
//            $uv->out = isset($outData[0]) ? date('Y-m-d', strtotime($outData[0]->operation_date)) : '';
//            $uv->in = isset($inData[0]) ? date('Y-m-d', strtotime($inData[0]->operation_date)) : '';
//
//
//            //日销
//            $s_start_time = strtotime($start_time);
//            $s_end_time = strtotime($start_time);
//            $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
//            $day_quantity_ordered = 0;
//            if ($uv->quantity_ordered > 0) {
//                $day_quantity_ordered = round($uv->quantity_ordered / $day, 2);
//            }
//
//            $fba_inventory = $uv->in_warehouse_inventory + $uv->reserved_inventory + $uv->in_road_inventory;
//
//            if ($day_quantity_ordered == 0) {
//                $uv->tongAn_inventory_day = 999;
//                $uv->fba_inventory = 999;
//            }
//
//            if ($uv->tongAn_inventory == 0) {
//                $uv->tongAn_inventory_day = 0;
//            }
//            if ($fba_inventory == 0) {
//                $uv->fba_inventory = 0;
//            }
//
//            if ($day_quantity_ordered > 0 && $uv->tongAn_inventory > 0) {
//                //同安库存周转天数=同安库存/日销
//                $uv->tongAn_inventory_day = round($uv->tongAn_inventory / $day_quantity_ordered, 2);
//            }
//            if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
//                //fba库存周转天数=在仓+预留+在途/日销
//                $uv->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
//            }
//        }
//
//
//        return [
//            'data' => $skus,
//            'totalnum' => $totalNum,
//        ];
//    }

    //获取数据统计与分析报表-SKU列表
    public function getDatawholeSkuDetail($params)
    {
        $category_id = isset($params['category_id']) ? $params['category_id'] : 6;
        $today = date('Y-m-d', time());//当天
        $dgday = isset($params['dgday']) ? $params['dgday'] : $today;
        $todaystart = date('Y-m-d 00:00:00', time());//当天
        $todayend = date('Y-m-d 23:59:59', time());//当天
        $start_time = isset($params['start_time']) ? $params['start_time'] : $todaystart;
        $end_time = isset($params['end_time']) ? $params['end_time'] : $todayend;
        $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
        $catequery['category_id'] = $category_id;
        $sku = isset($params['sku']) ? $params['sku'] : 'LT-GLBikini-001-17';

        //获取库存
        $Inventoryquery['category_id'] = $category_id;
        $Inventoryquery['sku'] = $sku;
        $Inventory = $this->getInventoryByOther($Inventoryquery);


        $query['start_time'] = $start_time;
        $query['end_time'] = $end_time;
        $query['dgday'] = $dgday;
        $query['category_id'] = $category_id;
        $query['sku'] = $sku;
        //根据店铺获取发货与销量
        //获取发货与销量
        $Datawhole = $this->getDatawholeByOther($query);
        $return = array_merge($Inventory, $Datawhole);
        $return['sku'] = $sku;
        return $return;
    }

    //获取库存-更改字段
    public function getInventoryByOther($params)
    {

        $where = "1=1";
        $bwhere = "1=1";

        //根据分类
        if (!empty($params['category_id'])) {
            $where .= " and b.category_id = {$params['category_id']}";
            $bwhere .= " and category_id = {$params['category_id']}";
        }
        //根据店铺
        if (!empty($params['shop_id'])) {
            $where .= " and b.shop_id = {$params['shop_id']} ";
            $bwhere .= " and shop_id = {$params['shop_id']} ";
        }
        //根据运营
        if (!empty($params['user_id'])) {
            $where .= " and b.user_id = {$params['user_id']} ";
            $bwhere .= " and user_id = {$params['user_id']} ";
        }
        //根据spu
        if (!empty($params['spu'])) {
            $where .= " and b.spu = '{$params['spu']}' ";
            $bwhere .= " and spu = '{$params['spu']}' ";
        }
        //根据sku
        if (!empty($params['sku'])) {
            //param_style==1时为 getDatawholeCustoms()、getDatawholeCustomsSku方法查询 where in sku
            if (isset($params['param_style']) && $params['param_style'] == 1) {
                $where .= " and b.order_source_sku in ({$params['sku']}) ";
                $bwhere .= " and sellersku in ({$params['sku']}) ";
            } else {
                $where .= " and b.order_source_sku = '{$params['sku']}' ";
                $bwhere .= " and sellersku = '{$params['sku']}' ";
            }

        }

        // 获取仓库库存
        $warehouseSql = "SELECT DISTINCT(b.client_sku),
        a.asin,a.warehouse_id,a.good_num,a.api_update_time
        FROM
            saihe_inventory a
        LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
        WHERE  
            $where
        AND 
        a.warehouse_id in (2,386,560)";

        // SELECT
        // a.asin,a.warehouse_id,a.good_num,a.api_update_time
        // FROM
        // saihe_inventory a
        // LEFT JOIN saihe_product_detail b ON a.sku = b.saihe_sku
        // WHERE
        // 1=1 and b.category_id = 20
        // AND
        // a.warehouse_id in (2,386)
        //运行时间 0.097
        $warehouseStore = DB::select($warehouseSql);

        $inventory = array();
        $inventory['tongAn_inventory'] = 0;//同安仓库存
        $inventory['quanZhou_inventory'] = 0;//同安仓库存
        if (!empty($warehouseStore)) {
            foreach ($warehouseStore as $val) {
                //同安仓库库存
                if (in_array($val->warehouse_id, [2,386])){
                    $inventory['tongAn_inventory'] += $val->good_num;
                }
                // 泉州库存
                if ($val->warehouse_id == 560){
                    $inventory['quanZhou_inventory'] += $val->good_num;
                }
            }
        }


        $AMZinventorySql = "SELECT
        sum(instock_supply_quantity) as instock_supply_quantity,sum(in_bound_num) as in_bound_num,sum(transfer_num) as transfer_num,update_time
        FROM
        product_detail
        WHERE  
            $bwhere";
        // SELECT
        // instock_supply_quantity,in_bound_num,transfer_num,update_time
        // FROM
        // product_detail
        // WHERE
        // 1=1 and category_id = 20
        //运行时间 0.045
        // var_dump($AMZinventorySql);

        $AMZinventory = DB::select($AMZinventorySql);
        $inventory['in_warehouse_inventory'] = 0;//fba在仓库存
        $inventory['reserved_inventory'] = 0;//预留库存
        $inventory['in_road_inventory'] = 0;//在途库存
        if (!empty($AMZinventory)) {
            foreach ($AMZinventory as $val) {
                //仓库 
                $inventory['in_warehouse_inventory'] = $val->instock_supply_quantity;
                $inventory['reserved_inventory'] = $val->transfer_num;
                $inventory['in_road_inventory'] = $val->in_bound_num;
            }
        }
        return $inventory;
    }

    //获取销量与发货-更改字段
    public function getDatawholeByOther($params)
    {
//        var_dump($params);die;
        $where = '1=1';
        $bwhere = '1=1';
        //根据分类
        if (!empty($params['category_id'])) {
            $where = "category_id = {$params['category_id']}";
            $bwhere = "d.category_id = {$params['category_id']}";
        }
        //根据店铺
        if (!empty($params['shop_id'])) {
            $where .= " and shop_id = {$params['shop_id']} ";
            $bwhere .= " and d.shop_id = {$params['shop_id']} ";
        }
        //根据运营
        if (!empty($params['user_id'])) {
            $where .= " and user_id = {$params['user_id']} ";
            $bwhere .= " and b.request_userid = {$params['user_id']} ";
        }
        //根据spu
        if (!empty($params['spu'])) {
            $where .= " and spu = '{$params['spu']}' ";
            $bwhere .= " and d.spu = '{$params['spu']}' ";
        }
        //根据sku
        if (!empty($params['sku'])) {
            //param_style==1时为 getDatawholeCustoms()、getDatawholeCustomsSku方法查询 where in sku
            if (isset($params['param_style']) && $params['param_style'] == 1) {
                $where .= " and seller_sku in ({$params['sku']}) ";
                $bwhere .= " and d.sku in ({$params['sku']}) ";
            } else {
                $where .= " and seller_sku = '{$params['sku']}' ";
                $bwhere .= " and d.sku = '{$params['sku']}' ";
            }

        }

        $today = date('Y-m-d', time());//当天
        $todaystart = date('Y-m-d 00:00:00', time());//当天
        $todayend = date('Y-m-d 23:59:59', time());//当天
        //查询类型
        $start_time = isset($params['start_time']) ? $params['start_time'] : $todaystart;
        $end_time = isset($params['end_time']) ? $params['end_time'] : $todayend;
        $start_time = date('Y-m-d 00:00:00', strtotime($start_time));
        $end_time = date('Y-m-d 23:59:59', strtotime($end_time));
        $dgday = isset($params['dgday']) ? $params['dgday'] : $today;


        //销量
        $wkSql = "select SUM(quantity_ordered) as quantity_ordered  from amazon_order_item where {$where} and amazon_time BETWEEN '{$start_time}' and '{$end_time}' and order_status !='Canceled'";
        // select SUM(quantity_ordered) as quantity_ordered from amazon_order_item where 1=1 and category_id = 20 and
        // unix_timestamp(purchase_date_show) BETWEEN 1648742400 and 1651161600
        // 1.7s;
        //加category_id索引后 0.9s;
        //加category_id purchase_date复合索引后0.03s;

        $wkData = DB::select($wkSql);


        $res['quantity_ordered'] = $wkData['0']->quantity_ordered ?? 0;


        //获取同安仓补货申请及明细
        $buhuoSql = "SELECT
        b.warehouse,
        d.request_num,
        d.transportation_mode_name,
        d.transportation_type
        FROM
        amazon_buhuo_detail d
        LEFT JOIN amazon_buhuo_request b ON d.request_id = b.id 
        WHERE
            $bwhere
        AND
        b.request_time  BETWEEN '{$start_time}' and '{$end_time}' 
        AND
        b.request_status in (4,5,6,7,8) 
        AND 
        b.warehouse in (1,2,3);";

        // SELECT
        // d.courier_num,
        // d.shipping_num,
        // d.air_num
        // FROM
        // amazon_buhuo_detail d
        // LEFT JOIN amazon_buhuo_request b ON d.request_id = b.id
        // WHERE
        // 1=1 and d.category_id = 20
        // AND
        // b.request_time LIKE '2022-04-26%'
        // AND
        // b.request_status in (1,2)
        //0.027s
        $buhuoData = DB::select($buhuoSql);
        // 同安
        $tongan_courier_num = 0; //快递
        $tongan_shipping_num = 0; //海运
        $tongan_air_num = 0; //空运
        $tongan_railway_num = 0;
        $tongan_kahang_num = 0;
        // 泉州
        $quanzhou_courier_num = 0; //快递
        $quanzhou_shipping_num = 0; //海运
        $quanzhou_air_num = 0; //空运
        $quanzhou_railway_num = 0;
        $quanzhou_kahang_num = 0;
        // 云仓
        $cloud_courier_num = 0; //快递
        $cloud_shipping_num = 0; //海运
        $cloud_air_num = 0; //空运
        $cloud_railway_num = 0;
        $cloud_kahang_num = 0;

        foreach ($buhuoData as $dgval) {
            if ($dgval->warehouse = 1){
                $num = $this->_getTransportationTypeNum($dgval);
                $tongan_courier_num += $num['courier_num'];
                $tongan_shipping_num += $num['shipping_num'];
                $tongan_air_num += $num['air_num'];
                $tongan_railway_num += $num['railway_num'];
                $tongan_kahang_num += $num['kahang_num'];
            }
            if ($dgval->warehouse = 2){
                $num = $this->_getTransportationTypeNum($dgval);
                $quanzhou_courier_num += $num['courier_num'];
                $quanzhou_shipping_num += $num['shipping_num'];
                $quanzhou_air_num += $num['air_num'];
                $quanzhou_railway_num += $num['railway_num'];
                $quanzhou_kahang_num += $num['kahang_num'];
            }
            if ($dgval->warehouse = 3){
                $num = $this->_getTransportationTypeNum($dgval);
                $cloud_courier_num += $num['courier_num'];
                $cloud_shipping_num += $num['shipping_num'];
                $cloud_air_num += $num['air_num'];
                $cloud_railway_num += $num['railway_num'];
                $cloud_kahang_num += $num['kahang_num'];
            }
        }
        $res['tongan_courier_num'] = $tongan_courier_num;
        $res['tongan_shipping_num'] = $tongan_shipping_num;
        $res['tongan_air_num'] = $tongan_air_num;
        $res['tongan_railway_num'] = $tongan_railway_num;
        $res['tongan_kahang_num'] = $tongan_kahang_num;

        $res['quanzhou_courier_num'] = $quanzhou_courier_num;
        $res['quanzhou_shipping_num'] = $quanzhou_shipping_num;
        $res['quanzhou_air_num'] = $quanzhou_air_num;
        $res['quanzhou_railway_num'] = $quanzhou_railway_num;
        $res['quanzhou_kahang_num'] = $quanzhou_kahang_num;

        $res['cloud_courier_num'] = $cloud_courier_num;
        $res['cloud_shipping_num'] = $cloud_shipping_num;
        $res['cloud_air_num'] = $cloud_air_num;
        $res['cloud_railway_num'] = $cloud_railway_num;
        $res['cloud_kahang_num'] = $cloud_kahang_num;

        // 三种运输方式总数量
        $res['courier_num'] = $tongan_courier_num + $quanzhou_courier_num + $cloud_courier_num;
        $res['shipping_num'] = $tongan_shipping_num + $quanzhou_shipping_num + $cloud_shipping_num;
        $res['air_num'] = $tongan_air_num + $quanzhou_air_num + $cloud_air_num;
        $res['railway_num'] = $tongan_railway_num + $quanzhou_railway_num + $cloud_railway_num;
        $res['kahang_num'] = $tongan_kahang_num + $quanzhou_kahang_num + $cloud_kahang_num;

        return $res;
    }

    private function _getTransportationTypeNum($data)
    {
        $result = [
            'courier_num' => 0,
            'shipping_num' => 0,
            'air_num' => 0,
            'railway_num' => 0,
            'kahang_num' => 0
        ];

        switch ($data->transportation_type)
        {
            case 1:
                // 海运
                $result['shipping_num'] = $data->reqeust_num;
                break;
            case 2:
                // 快递
                $result['courier_num'] = $data->reqeust_num;
                break;
            case 3:
                // 空运
                $result['air_num'] = $data->reqeust_num;
                break;
            case 4:
                // 铁路
                $result['railway_num'] = $data->reqeust_num;
                break;
            case 5:
                // 卡航
                $result['kahang_num'] = $data->reqeust_num;
                break;
            default:
                break;
        }

        return $result;
    }

    //数据报表-店铺列表
    public function getDatawholeShop($params)
    {
        $where = 'platform_id = 5 and state=1';
        if (isset($params['shop_id'])) {
            $where .= " and Id = {$params['shop_id']}";
        }
        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);

        $limitsql = "LIMIT $page,$limit";
        $sql = "select SQL_CALC_FOUND_ROWS Id,shop_name from shop where {$where} $limitsql";
        $store = Db::select($sql);
        $totalNum = DB::select("SELECT FOUND_ROWS() as total")[0]->total;
        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
        $shopId = implode(',', array_column($store, 'Id'));
        $report_sql = "select shop_id,sum(quantity) as return_num from amazon_report where shop_id in ({$shopId}) and return_date between '{$start_time}' and '{$end_time}' group by shop_id ";
        $report = Db::select($report_sql);

        foreach ($store as $key => $value) {
            $inventoryParams['shop_id'] = $value->Id;

            //获取库存
            $Inventory = $this->getInventoryByOther($inventoryParams);
            //获取发货与销量
            $Datawhole = $this->getDatawholeByOther($inventoryParams);

            //转化率
            $conversion_rate = 0;
            $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where shop_id = '{$value->Id}' and ds between '{$start_time}' and '{$end_time}'";
            $percentage = Db::select($percentage_sql);
            $session_percentage = $percentage[0]->session_percentage ?? 0;
            $conversion_rate = 0;
            if ($session_percentage > 0 && $Datawhole['quantity_ordered'] > 0) {
                $quantity_ordered = $Datawhole['quantity_ordered'];
                $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
            }
            $store[$key]->conversion_rate = (int)$conversion_rate;

            $store[$key]->quantity_ordered = $Datawhole['quantity_ordered'];
            $store[$key]->courier_num = $Datawhole['courier_num'];
            $store[$key]->shipping_num = $Datawhole['shipping_num'];
            $store[$key]->air_num = $Datawhole['air_num'];
            $store[$key]->tongAn_inventory = (int)$Inventory['tongAn_inventory'];
            $store[$key]->in_warehouse_inventory = (int)$Inventory['in_warehouse_inventory'];
            $store[$key]->reserved_inventory = (int)$Inventory['reserved_inventory'];
            $store[$key]->in_road_inventory = (int)$Inventory['in_road_inventory'];
            $store[$key]->return_num = 0;
            $store[$key]->return_rate = 0;
            foreach ($report as $k => $v) {
                if ($value->Id == $v->shop_id) {
                    $store[$key]->return_num = (int)$v->return_num;
                    $store[$key]->return_rate = $Datawhole['quantity_ordered'] > 0 ? round($v->return_num / $Datawhole['quantity_ordered'], 4) * 100 : 0;
                }
            }
        }

        return [
            'data' => $store,
            'totalnum' => $totalNum,
        ];

    }

    //数据报表-运营人员列表
    public function getDatawholeUser($params)
    {
        $where = 'om.organize_id = 19';
        if (isset($params['user_id'])) {
            $where .= " and om.user_id = {$params['user_id']}";
        }
        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);

        $limitsql = "LIMIT $page,$limit";
        $sql = "select SQL_CALC_FOUND_ROWS om.user_id,account 
                    from organizes_member om 
                    left join users u on u.Id=om.user_id
                    where {$where} and u.state=1 $limitsql";
        $user = Db::select($sql);
        $totalNum = DB::select("SELECT FOUND_ROWS() as total")[0]->total;
        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
        $userId = implode(',', array_column($user, 'user_id'));
        $report_sql = "select  user_id,sum(quantity) as return_num
                            from amazon_report 
                            where user_id in ({$userId}) and return_date between '{$start_time}' and '{$end_time}'
                            group by user_id";//
        $report = Db::select($report_sql);
        foreach ($user as $key => $value) {
            $inventoryParams['user_id'] = $value->user_id;
            //获取库存
            $Inventory = $this->getInventoryByOther($inventoryParams);
            //获取发货与销量
            $Datawhole = $this->getDatawholeByOther($inventoryParams);

            //转化率
            $conversion_rate = 0;
            $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where user_id = '{$value->user_id}' and ds between '{$start_time}' and '{$end_time}'";
            $percentage = Db::select($percentage_sql);
            $session_percentage = $percentage[0]->session_percentage ?? 0;
            $conversion_rate = 0;
            if ($session_percentage > 0 && $Datawhole['quantity_ordered'] > 0) {
                $quantity_ordered = $Datawhole['quantity_ordered'];
                $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
            }
            $user[$key]->conversion_rate = (int)$conversion_rate;

            $user[$key]->quantity_ordered = $Datawhole['quantity_ordered'];
            $user[$key]->courier_num = $Datawhole['courier_num'];
            $user[$key]->shipping_num = $Datawhole['shipping_num'];
            $user[$key]->air_num = $Datawhole['air_num'];
            $user[$key]->tongAn_inventory = (int)$Inventory['tongAn_inventory'];
            $user[$key]->in_warehouse_inventory = (int)$Inventory['in_warehouse_inventory'];
            $user[$key]->reserved_inventory = (int)$Inventory['reserved_inventory'];
            $user[$key]->in_road_inventory = (int)$Inventory['in_road_inventory'];
            $user[$key]->return_num = 0;
            $user[$key]->return_rate = 0;
            foreach ($report as $k => $v) {
                if ($value->user_id == $v->user_id) {
                    $user[$key]->return_num = (int)$v->return_num;
                    $user[$key]->return_rate = $Datawhole['quantity_ordered'] > 0 ? round($v->return_num / $Datawhole['quantity_ordered'], 4) * 100 : 0;
                }
            }

        }
//        var_dump($report);die;
        return [
            'data' => $user,
            'totalnum' => $totalNum,
        ];
    }

    public function getDatawholeAsin($params)
    {
        $where = '1=1';
        if (isset($params['father_asin'])) {
            $where .= " and father_asin = '{$params['father_asin']}'";
        }
        if (isset($params['category_id'])) {
            $inventoryParams['category_id'] = $params['category_id'];
            $where .= " and category_id = {$params['category_id']}";
        }
        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page = $this->getLimitParam($page, $limit);

        $limitsql = "LIMIT $page,$limit";
        $sql = "select SQL_CALC_FOUND_ROWS spu from amazon_skulist where {$where} and father_asin!='' group by spu $limitsql";
        $spu = Db::select($sql);
        $totalNum = DB::select("SELECT FOUND_ROWS() as total")[0]->total;
        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
        if (empty($spu)) {
            return [
                'data' => [],
                'totalnum' => 0,
            ];
        }
        $spu_arr = array_column($spu, 'spu');
        $spu_str = implode(',', array_map(
                function ($str) {
                    return sprintf("'%s'", $str);
                }, $spu_arr
            )
        );
        $report_sql = "select spu,sum(quantity) as return_num from amazon_report where spu in ({$spu_str}) and return_date between '{$start_time}' and '{$end_time}' and category_id = {$params['category_id']} group by spu ";
        $report = Db::select($report_sql);
        foreach ($spu as $key => $value) {
            if ($value->spu) {
                $inventoryParams['spu'] = $value->spu;
                $img_sql = "select img from amazon_skulist where spu='{$value->spu}'";//APOH700010
                $img = Db::select($img_sql);
                $img_arr = array_filter(array_column($img, 'img'));
                $spu_img = '';
                if (!empty($img_arr)) {
                    $spu_img = reset($img_arr);
                }
                $spu[$key]->img = $spu_img;

                //获取库存
                $Inventory = $this->getInventoryByOther($inventoryParams);
                //获取发货与销量
                $Datawhole = $this->getDatawholeByOther($inventoryParams);

                //转化率
                $conversion_rate = 0;
                $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where spu = '{$value->spu}' and ds between '{$start_time}' and '{$end_time}'";
                $percentage = Db::select($percentage_sql);
                $session_percentage = $percentage[0]->session_percentage ?? 0;
                if ($session_percentage > 0 && $Datawhole['quantity_ordered'] > 0) {
                    $quantity_ordered = $Datawhole['quantity_ordered'];
                    $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
                }
                $spu[$key]->conversion_rate = (int)$conversion_rate;

                $spu[$key]->quantity_ordered = $Datawhole['quantity_ordered'];
                $spu[$key]->courier_num = $Datawhole['courier_num'];
                $spu[$key]->shipping_num = $Datawhole['shipping_num'];
                $spu[$key]->air_num = $Datawhole['air_num'];
                $spu[$key]->tongAn_inventory = (int)$Inventory['tongAn_inventory'];
                $spu[$key]->tongAn_deduct_inventory = (int)($Inventory['tongAn_inventory'] - $Datawhole['courier_num'] - $Datawhole['shipping_num'] - $Datawhole['air_num']) - $Datawhole['railway_num'] - $Datawhole['kahang_num'];
                $spu[$key]->in_warehouse_inventory = (int)$Inventory['in_warehouse_inventory'];
                $spu[$key]->reserved_inventory = (int)$Inventory['reserved_inventory'];
                $spu[$key]->in_road_inventory = (int)$Inventory['in_road_inventory'];
                //生产数据
                $productionSql = "select order_num,shipment_num from production_order where style_no='{$value->spu}'";
                $productionData = DB::select($productionSql);
                $spu[$key]->order_num = isset($productionData[0]) ? $productionData[0]->order_num : 0;
                $spu[$key]->shipment_num = isset($productionData[0]) ? $productionData[0]->shipment_num : 0;
                $spu[$key]->return_num = 0;
                $spu[$key]->return_rate = 0;
                foreach ($report as $k => $v) {
                    if ($value->spu == $v->spu) {
                        $spu[$key]->return_num = (int)$v->return_num;
                        $spu[$key]->return_rate = $Datawhole['quantity_ordered'] > 0 ? round($v->return_num / $Datawhole['quantity_ordered'], 4) * 100 : 0;
                    }

                }
                //出入库时间
                //出
                $outSql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu='{$value->spu}' and type =1 order by max desc limit 1 ";
                $outData = DB::select($outSql);
                //入
                $insql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu='{$value->spu}' and type =2 order by max desc limit 1 ";
                $inData = DB::select($insql);

                $spu[$key]->out = isset($outData[0]) ? date('Y-m-d', strtotime($outData[0]->operation_date)) : '';
                $spu[$key]->in = isset($inData[0]) ? date('Y-m-d', strtotime($inData[0]->operation_date)) : '';


                //日销
                $s_start_time = strtotime($start_time);
                $s_end_time = strtotime($end_time);
                $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
                $day_quantity_ordered = 0;
                if ($Datawhole['quantity_ordered'] > 0) {
                    $day_quantity_ordered = round($Datawhole['quantity_ordered'] / $day, 2);
                }

                $fba_inventory = $spu[$key]->in_warehouse_inventory + $spu[$key]->reserved_inventory + $spu[$key]->in_road_inventory;

                if ($day_quantity_ordered == 0) {
                    $spu[$key]->tongAn_inventory_day = 999;
                    $spu[$key]->fba_inventory = 999;
                }

                if ($spu[$key]->tongAn_inventory == 0) {
                    $spu[$key]->tongAn_inventory_day = 0;
                }
                if ($fba_inventory == 0) {
                    $spu[$key]->fba_inventory = 0;
                }

                if ($day_quantity_ordered > 0 && $spu[$key]->tongAn_inventory > 0) {
                    //同安库存周转天数=同安库存/日销
                    $spu[$key]->tongAn_inventory_day = round($spu[$key]->tongAn_inventory / $day_quantity_ordered, 2);
                }
                if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
                    //fba库存周转天数=在仓+预留+在途/日销
                    $spu[$key]->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
                }


            }

        }
        return [
            'data' => $spu,
            'totalnum' => $totalNum,
        ];
    }

    public function getDatawholeFatherAsin($params)
    {
//        $spu = $this->GetNewSpu($params['spu']);

        //根据分类
        if (!empty($params['category_id'])) {
            $where['category_id'] = $params['category_id'];
            $bwhere['category_id'] = $params['category_id'];
        }

        if (isset($params['father_asin'])) {
            $where['parent_asin'] = $params['father_asin'];
        }

        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $limitPage = $page * $limit;
        $pageNum = $page > 1 ? $page - 1 : 0;
        //查询product_detail表parent_asin字段
        //$fatherAsinQuery = Db::table('product_detail')->select('parent_asin')->groupBy('parent_asin');

        $fatherAsinQuery = Db::table('product_detail')
            //->select('parent_asin','sum(instock_supply_quantity) as instock_supply_quantity','sum(in_bound_num) as in_bound_num','sum(transfer_num) as transfer_num','update_time')
            ->select([
                DB::raw('sum(instock_supply_quantity) as in_warehouse_inventory'),
                DB::raw('sum(in_bound_num) as in_road_inventory'),
                DB::raw('sum(transfer_num) as reserved_inventory'),
                'update_time',
                'parent_asin',
                'small_image as img'
            ])
            ->groupBy('parent_asin');

        if (isset($where)) {
            $fatherAsinQuery->where($where);
        }
        //总条数
        $pageCount = $fatherAsinQuery->count();
        $fatherAsin = $fatherAsinQuery
            ->where('parent_asin','!=','')
            ->limit($limitPage)
            ->offset($pageNum)
            ->get()
            ->toArray();


        if (empty($fatherAsin)) {
            return [
                'data' => [],
                'totalnum' => 0,
            ];
        }
        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());

        $asinArr = array_column($fatherAsin, 'parent_asin');
        //根据parent_asin查询product_detail表
        $skuQuery = Db::table('product_detail')->select('parent_asin', 'sellersku')->whereIn('parent_asin', $asinArr);
        if (isset($bwhere)) {
            $skuQuery->where($bwhere);
        }
        $sku = $skuQuery->get()->toArray();
        $skuStr = array_column($sku, 'sellersku');
        $inventoryParams['sku'] = $skuStr;
        $inventoryParams['param_style'] = 1;
//        var_dump($sku);die;
        //获取库存
//        $Inventory = $this->getInventoryByOther($inventoryParams);


        //销量
        $wkData = Db::table('amazon_order_item')
            ->select([
                Db::raw('sum(quantity_ordered) as quantity_ordered'),
                'seller_sku'
            ])
            ->whereIn('seller_sku', $skuStr)
            ->whereBetween('amazon_time', [$start_time, $end_time])
            ->groupBy('seller_sku')
            ->get()
            ->toArray();
        //库存
        $skuData = Db::table('saihe_inventory as a')
            ->select([
                Db::raw('sum(a.good_num) as good_num'),
                'b.order_source_sku'
            ])
            ->leftJoin('saihe_product_detail as b', 'a.sku', '=', 'b.saihe_sku')
            ->whereIn('b.order_source_sku', $skuStr)
            ->whereIn('a.warehouse_id', [2, 386])
            ->where('good_num', '!=', 0)
            ->groupBy('b.order_source_sku')
            ->get()
            ->toArray();

        //发货
        $dgData = Db::table('amazon_buhuo_detail as d')
            ->select('d.request_num', 'd.transportation_mode_name', 'd.transportation_type', 'd.sku')
            ->leftJoin('amazon_buhuo_request as b', 'd.request_id', '=', 'b.id')
            ->whereBetween('b.request_time', [$start_time, $end_time])
            ->whereIn('b.request_status', [4, 5, 6, 7, 8])
            ->whereIn('d.sku', $skuStr)
            ->get()
            ->toArray();


        $outData = Db::table('saihe_warehouse_log')
            ->select([
                Db::raw('UNIX_TIMESTAMP(operation_date)as max'),
                'operation_date',
                'sku'
            ])
            ->whereIn('sku', $skuStr)
            ->where('type', 1)
            ->orderBy('max', 'desc')
            ->groupBy('sku')
            ->get()
            ->toArray();
        $inData = Db::table('saihe_warehouse_log')
            ->select([
                Db::raw('UNIX_TIMESTAMP(operation_date)as max'),
                'operation_date',
                'sku'
            ])
            ->whereIn('sku', $skuStr)
            ->where('type', 2)
            ->orderBy('max', 'desc')
            ->groupBy('sku')
            ->get()
            ->toArray();

//        var_dump($wkData);die;

        foreach ($sku as $key => $value) {
            $sku[$key]->good_num = 0;
            $sku[$key]->quantity_ordered = 0;
            $sku[$key]->courier_num = 0;
            $sku[$key]->shipping_num = 0;
            $sku[$key]->air_num = 0;
            $sku[$key]->railway_num = 0;
            $sku[$key]->kahang_num = 0;
            $sku[$key]->out = '';
            $sku[$key]->in = '';
            $sku[$key]->tongAn_inventory = 0;
            foreach ($skuData as $k => $v) {

                if ($value->sellersku == $v->order_source_sku) {
                    //仓库
                    $sku[$key]->tongAn_inventory = $v->good_num;
                }
            }

            foreach ($wkData as $ke => $va) {
                if ($value->sellersku == $va->seller_sku) {
                    //销量
                    $sku[$key]->quantity_ordered = $va->quantity_ordered;
                }
            }

            foreach ($dgData as $ks => $val) {
                if ($value->sellersku == $val->sku) {
                    switch ($val->transportation_type){
                        case 1:
                            // 海运
                            $sku[$key]->shipping_num += $val->request_num;//海运
                            break;
                        case 2:
                            // 快递
                            $sku[$key]->courier_num += $val->request_num;//快递
                            break;
                        case 3:
                            // 空运
                            $sku[$key]->air_num += $val->request_num;//空运
                            break;
                        case 4:
                            // 铁路
                            $sku[$key]->railway_num = $val->request_num;
                            break;
                        case 5:
                            // 卡航
                            $sku[$key]->kahang_num = $val->request_num;
                            break;
                        default:
                            break;
                    }
                }
            }

            //出库时间
            foreach ($outData as $outKey => $outValue) {
                if ($value->sellersku == $outValue->sku) {
                    $sku[$key]->out = date('Y-m-d', strtotime($outValue->operation_date));
                }
            }
            //入库时间
            foreach ($inData as $inKey => $inValue) {
                if ($value->sellersku == $inValue->sku) {
                    $sku[$key]->in = date('Y-m-d', strtotime($inValue->operation_date));
                }
            }
        }

        //退货
        $return = Db::table('amazon_return_order')
            ->select([
                Db::raw('count(quantity) as quantity'),
                'father_asin'
            ])
            ->whereIn('father_asin', $asinArr)
            ->whereBetween('beijing_date', [$start_time, $end_time])
            ->groupBy('father_asin')
            ->get()
            ->toArray();

        foreach ($fatherAsin as $faKey => $faVal) {
            $fatherAsin[$faKey]->return_num = 0;
            $fatherAsin[$faKey]->tongAn_inventory = 0;
            $fatherAsin[$faKey]->good_num = 0;
            $fatherAsin[$faKey]->quantity_ordered = 0;
            $fatherAsin[$faKey]->courier_num = 0;
            $fatherAsin[$faKey]->shipping_num = 0;
            $fatherAsin[$faKey]->air_num = 0;
            $fatherAsin[$faKey]->railway_num = 0;
            $fatherAsin[$faKey]->kahang_num = 0;
            $fatherAsin[$faKey]->out = '';
            $fatherAsin[$faKey]->in = '';
            $fatherAsin[$faKey]->conversion_rate = 0;
            foreach ($return as $reKey => $reVal) {
                if ($faVal->parent_asin == $reVal->father_asin) {
                    $fatherAsin[$faKey]->return_num = $reVal->quantity;//退货数
                }
            }

            foreach ($sku as $skuKey => $skValue) {
                if ($faVal->parent_asin == $skValue->parent_asin) {
                    $fatherAsin[$faKey]->good_num += $skValue->tongAn_inventory;
                    $fatherAsin[$faKey]->good_num += $skValue->good_num;
                    $fatherAsin[$faKey]->quantity_ordered += $skValue->quantity_ordered;
                    $fatherAsin[$faKey]->courier_num += $skValue->courier_num;
                    $fatherAsin[$faKey]->shipping_num += $skValue->shipping_num;
                    $fatherAsin[$faKey]->air_num += $skValue->air_num;
                    $fatherAsin[$faKey]->railway_num += $skValue->railway_num;
                    $fatherAsin[$faKey]->kahang_num += $skValue->kahang_num;
                    $fatherAsin[$faKey]->out = $skValue->out;
                    $fatherAsin[$faKey]->out = $skValue->in;
                }
            }
            $fatherAsin[$faKey]->tongAn_deduct_inventory = (int)($fatherAsin[$faKey]->tongAn_inventory - $fatherAsin[$faKey]->courier_num - $fatherAsin[$faKey]->shipping_num - $fatherAsin[$faKey]->air_num - $fatherAsin[$faKey]->railway_num - $fatherAsin[$faKey]->kahang_num);

            $fatherAsin[$faKey]->return_rate = $fatherAsin[$faKey]->quantity_ordered > 0 ? round($fatherAsin[$faKey]->return_num / $fatherAsin[$faKey]->quantity_ordered, 4) * 100 : 0;
            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
            $day_quantity_ordered = 0;
            if ($fatherAsin[$faKey]->quantity_ordered > 0) {
                $day_quantity_ordered = round($fatherAsin[$faKey]->quantity_ordered / $day, 2);
            }
            $fba_inventory = $fatherAsin[$faKey]->in_warehouse_inventory + $fatherAsin[$faKey]->reserved_inventory + $fatherAsin[$faKey]->in_road_inventory;

            if ($day_quantity_ordered == 0) {
                $fatherAsin[$faKey]->tongAn_inventory_day = 999;
                $fatherAsin[$faKey]->fba_inventory = 999;
            }

            if ($fatherAsin[$faKey]->tongAn_inventory == 0) {
                $fatherAsin[$faKey]->tongAn_inventory_day = 0;
            }
            if ($fba_inventory == 0) {
                $fatherAsin[$faKey]->fba_inventory = 0;
            }

            if ($day_quantity_ordered > 0 && $fatherAsin[$faKey]->tongAn_inventory > 0) {
                //同安库存周转天数=同安库存/日销
                $fatherAsin[$faKey]->tongAn_inventory_day = round($fatherAsin[$faKey]->tongAn_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $fatherAsin[$faKey]->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
            }
        }


        return [
            'data' => $fatherAsin,
            'totalnum' => $pageCount,
        ];
    }

    //fasin数据报表-新
    public function DatawholeFasin($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $start_time = date('Y-m-d',time());
        $end_time = date('Y-m-d 23:59:59',time());

        if (isset($params['start_time'])) {
            $start_time = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end_time = $params['end_time'].' 23:59:59';
        }

        $list = Db::table('amazon_fasin');

        $shop_id = 0;

        if(isset($params['shop_id'])){
            $shop_id = $params['shop_id'];
            $list = $list->whereRaw("find_in_set({$shop_id},`shops`)");
        }

        //负责人 总负责人搜索
        $shop_model = db::table('shop');

        $is_shop = false;
        if(isset($params['shops_fz'])){
            $user_fz = $params['shops_fz'];
            $is_shop = true;
            $shop_model =  $shop_model->whereRaw("find_in_set({$user_fz},`user_fz`)");
        }

        if(isset($params['shops_fz_all'])){
            $user_fz_all = $params['shops_fz_all'];
            $is_shop = true;
            $shop_model =  $shop_model->where('user_fz_all',$user_fz_all);
        }

        if($is_shop){
            $shop_res =  $shop_model->get()->toArray();
            $shop_ids = array_column($shop_res,'Id');
            // var_dump($shop_ids);
            foreach ($shop_ids  as $k => $sid) {
                # code...
                if ($k==0){
                    $list = $list->orwhereRaw("find_in_set({$sid},`shops`)");
                }else{
                    $list = $list->orwhereRaw("find_in_set({$sid},`shops`)");
                }
                
            }
    
        }
       

        if(isset($params['fasin'])){
            $fasinList = explode(',', $params['fasin']);
            $list = $list->where(function($q) use ($fasinList){
                foreach ($fasinList as $fasin){
                    $q->orwhere('fasin', 'like', '%'.$fasin.'%');
                }
                return $q;
            });
//            $list = $list->where('fasin','like','%'.$params['fasin'].'%');
        }

        if(isset($params['fasin_code'])){
            $fasinCodeList = explode(',', $params['fasin_code']);
            $fasinCodeMdl = db::table('amazon_fasin_bind')->whereIn('fasin_code', $fasinCodeList)->groupBy('fasin')->get(['fasin']);
            $fasinCodeMdl = json_decode(json_encode($fasinCodeMdl), true);
            $list = $list->whereIn('fasin', array_column($fasinCodeMdl, 'fasin'));
//            $list = $list->where('fasin','like','%'.$params['fasin'].'%');
        }

        if(isset($params['user_id'])){
            $list = $list->where('user_id',$params['user_id']);
        }

        if(isset($params['type'])){
            $list = $list->where('type',$params['type']);
        }

        if(isset($params['one_cate_id'])){
            $list = $list->whereIn('one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $list = $list->whereIn('two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $list = $list->whereIn('three_cate_id',$params['three_cate_id']);
        }


        $is_self = $params['is_self']??1;


        $list = $list->where('is_self',$is_self);
       
        $totalnum = $list->get()->count();
        $list = $list->offset($pagenNum)->limit($limit)->get()->toArray();

        if($is_self==2){

            $fasin_res = [];

            $i = 0;

            foreach ($list as $v) {
                # code...
                $fasin_res[$i]['fasin'] = $v->fasin;
                $fasin_res[$i]['shop_name'] = $v->shop_name;
                $fasin_res[$i]['memo'] = $v->memo;
                $fasin_res[$i]['all_rank'] = 0;
                $fasin_res[$i]['cate_rank'] = 0;
                $rank = db::table('amazon_link_ranklog')->where('father_asin',$v->fasin)->orderby('id','desc')->first();
                if($rank){
                    $fasin_res[$i]['all_rank'] = $rank->all_num;
                    $fasin_res[$i]['cate_rank'] = $rank->cate_num;
                }
                $i++;
            }

            return ['data' => $fasin_res,'totalnum' => $totalnum];
            
        }
     

        // var_dump($list);

        $nlist = [];
        foreach ($list as $v) {
            # code...
            $nlist[$v->fasin] = $v;
        }

        $fasins = array_column($list,'fasin');



        //会话率查询
        $sessions_total = [];
        $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('fasin',$fasins)->where('sessions_total','>',0)->groupby('fasin')->select('fasin',db::raw('sum(sessions_total) as sessions_total'))->get();

        foreach ($sessions_res as $srv) {
            # code...
            $sessions_total[$srv->fasin] = $srv->sessions_total;
        }


        $fasin_res = $this->getfasins($fasins,$start_time, $end_time, $shop_id);


        $hday = ceil((strtotime($end_time)-strtotime($start_time))/86400);
        
        $fasinMessageMdl = DB::table('amazon_fasin_message')->where('fid', 0)->orderBy('created_at', 'DESC')->get();
        $fasinMessageAll = DB::table('amazon_fasin_message')->where('fid', '<>', 0)->get();
        foreach ($fasinMessageMdl as $item){
            $child = [];
            foreach ($fasinMessageAll as $msg){
                if ($item->id == $msg->fid){
                    $msg->content_type_name = Constant::FASIN_CONTENT_TYPE[$msg->content_type] ?? '';
                    $msg->is_currency_name = $msg->is_currency ? '通用型' : '一次性型';
                    $msg->file = json_decode($msg->file, true);
                    $msg->img = json_decode($msg->img, true);
//                            $msg->content = strip_tags($msg->content, '<br> <p> <a>');
                    $child[] = $msg;
                }
            }
            $item->child = $child;
            $item->content_type_name = Constant::FASIN_CONTENT_TYPE[$item->content_type] ?? '';
            $item->is_currency_name = $item->is_currency ? '通用型' : '一次性型';
            $item->file = json_decode($item->file, true);
            $item->img = json_decode($item->img, true);
//                    $item->content = strip_tags($item->content, '<br> <p> <a>');
        }
        $fasinBindMdl = db::table('amazon_fasin_bind')->get();

//        //查询库龄表
        $amazon_inventory_aged = DB::table('amazon_inventory_aged as a')
            ->leftJoin('self_sku as b', 'a.sku_id', '=', 'b.id');
        $date = date('Y-m-d', strtotime('-1 days'));
        if (isset($params['start_time']) && isset($params['end_time'])){
            $date = $params['end_time'];
            $amazon_inventory_aged = $amazon_inventory_aged->where('a.snapshot_date', $date);
        }
        $fasinList = array_column($fasin_res, 'fasin');
        $amazon_inventory_aged = $amazon_inventory_aged->whereIn('b.fasin', $fasinList);
        $amazon_inventory_aged = $amazon_inventory_aged->get(['a.*', 'b.fasin']);

        $thisWeek = [];
        $lastWeek = [];
        if (isset($params['start_time']) && isset($params['end_time'])){
            foreach ($amazon_inventory_aged as $a){
                if (isset($thisWeek[$a->fasin])){
                    $thisWeek[$a->fasin]['day_0_90'] += $a->day_0_90;
                    $thisWeek[$a->fasin]['day_91_180'] += $a->day_91_180;
                    $thisWeek[$a->fasin]['day_181_270'] += $a->day_181_270;
                    $thisWeek[$a->fasin]['day_271_365'] += $a->day_271_365;
                    $thisWeek[$a->fasin]['day_365'] += $a->day_365;
                }else{
                    $thisWeek[$a->fasin] = [
                        'day_0_90' => $a->day_0_90,
                        'day_91_180' => $a->day_91_180,
                        'day_181_270' => $a->day_181_270,
                        'day_271_365' => $a->day_271_365,
                        'day_365' => $a->day_365,
                    ];
                }
            }
        }

        foreach ($fasin_res as &$v) {
            # code...
            $fasin_result =  $nlist[$v['fasin']];
            $v['edit'] = $fasin_result;
            $v['memo'] =  $nlist[$v['fasin']]->memo ?? '';
//            $v['fasin_code'] =  $nlist[$v['fasin']]->fasin_code ?? '';
            $fasinBind = $this->GetFasinCodeNew($v['fasin']);
            $v['fasin_code'] =  array_column($fasinBind, 'fasin_code');
            $v['is_read'] = $this->GetFasinMessageRead($v['fasin']);
            $coreWord = [];
            $situation = [];
            $this_aged = $thisWeek[$v['fasin']] ?? [];
            $v['day_0_90'] = $this_aged['day_0_90'] ?? 0;
            $v['day_91_180'] = $this_aged['day_91_180'] ?? 0;
            $v['day_181_270'] = $this_aged['day_181_270'] ?? 0;
            $v['day_271_365'] = $this_aged['day_271_365'] ?? 0;
            $v['day_365'] = $this_aged['day_365'] ?? 0;
//            $v['last_aged'] = $lastWeek[$v['fasin']] ?? [];
            foreach($fasinBindMdl as $bind){
                if ($bind->fasin != $v['fasin']){
                    continue;
                }
                $coreWord[] = [
                    'fasin_code' => $bind->fasin_code,
                    'core_word' => $bind->core_word ?? '',
                    'strategy' => $bind->strategy ?? ''
                ];
                $situation[] = [
                    'fasin_code' => $bind->fasin_code,
                    'situation' => $bind->situation ?? ''
                ];
            }
            $v['core_word'] = $coreWord;
            $v['situation'] = $situation;
            $v['shops'] = [];
            $v['country_id'] = 0;




            $message = [];
            $i = 0;
            foreach ($fasinMessageMdl as $m){
                if ($i >4){
                    break;
                }
                if ($m->fasin == $v['fasin']){
                    $m->content1 = strip_tags($m->content);
                    $message[] = $m;
                    $i++;
                }
            }
            $v['message'] = $message;
            // $cus = db::table('self_sku')->where('fasin',$v['fasin'])->groupby("shop_id")->select("shop_id")->get();
            // if($cus){
            //     foreach ($cus as $cus_v) {
            //         $v['shops'][] = $this->GetShop($cus_v->shop_id)['shop_name']??'';
            //     }
            // }

            $shop_ids = explode(',',$fasin_result->shops);
            if(count($shop_ids)>0){
                foreach ($shop_ids as $shop_id) {
                    $shopres = $this->GetShop($shop_id);
                    if($shopres){
                        $v['shops'][] = $shopres['shop_name']??'';
                        $v['country_id'] = $shopres['country_id'] ?? 0;
                        if(!empty($shopres['user_fz'])){
                            $user_fz_ids = explode(',',$shopres['user_fz']);
                            foreach ($user_fz_ids as $fz_id) {
                                # code...
                                if($fz_id>0){
                                    $v['shops_fz'][] = $this->GetUsers($fz_id)['account'];
                                }
                            }

                        }
                        if($shopres['user_fz_all']>0){
                            $v['shops_fz_all'][] = $this->GetUsers($shopres['user_fz_all'])['account'];
                        }
                    }

                }
            }

            $v['user'] = '';
            $v['user_id'] = $fasin_result->user_id;

            $v['user'] = $this->GetUsers($fasin_result->user_id)['account'];


            $v['return_rate'] = 0;
            if($v['return_num']>0&&$v['order_num']>0){
                $v['return_rate'] = round($v['return_num']/$v['order_num']*100,2);
            }


            //总销售额sales_price 广告预算 广告实际花费ad_price广告销售额ad_sales  tacos（广告花费/销售额） acos（广告花费/广告销售额）
            $day = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.fasin',$v['fasin'])->whereBetween('b.ds', [$start_time, $end_time])->where('a.status',1)->select('b.user_id','a.sales_num','a.sales_price','a.ad_price','a.ad_sales','a.acos','a.tacos','a.week_total_flow')->get();
            $v['sales_price'] = 0;
            $v['ad_price'] = 0;
            $v['ad_sales'] = 0;
            $v['sales_num'] = 0;
            $v['week_total_flow'] = 0;
            $v['acos'] = 0;
            $v['tacos'] = 0;
            $v['type'] = $fasin_result->type;


            //广告预算=预算（2霸链接25%，1利润链接15%,3冲量20%，4清仓退货17%）*总销售额

            $ad_ys = 15/100;

            if($v['type']==3){
                $ad_ys = 20/100;
            }

            if($v['type']==2){
                $ad_ys = 25/100;
            }

            if($v['type']==4){
                $ad_ys = 17/100;
            }






            foreach ($day as $dv) {
                # code...

                $v['sales_price'] += $dv->sales_price;
                $v['ad_price'] += $dv->ad_price;
                $v['ad_sales'] += $dv->ad_sales;
                $v['sales_num'] += $dv->sales_num;
                $v['week_total_flow'] +=$dv->week_total_flow;
            }

            $v['order_num'] = $v['sales_num'];

            if($v['ad_price']>0&&$v['sales_price']>0){
                $v['tacos'] = round(($v['ad_price']/$v['sales_price'])*100,2);
            }

            if($v['ad_price']>0&&$v['ad_sales']>0){
                $v['acos'] = round(($v['ad_price']/$v['ad_sales'])*100,2);
            }


            $v['sales_price'] = round($v['sales_price'],2);
            $v['ad_price'] = round($v['ad_price'],2);
            $v['ad_sales'] = round($v['ad_sales'],2);

            $v['ad_budget'] = round($ad_ys*$v['sales_price'],2);


            // $v['all_rank'] = $fasin_result->all_rank;
            // $v['cate_rank'] = $fasin_result->cate_rank;

            $v['all_rank'] = 0;
            $v['cate_rank'] = 0;
            $rank = db::table('amazon_link_ranklog')->where('father_asin',$v['fasin'])->orderby('id','desc')->first();
            if($rank){
                $v['all_rank'] = $rank->all_num;
                $v['cate_rank'] = $rank->cate_num;
            }

            // $v['cate_name'] = '';

            $one = $this->GetCategory($fasin_result->one_cate_id)['name'];
            $three = $this->GetCategory($fasin_result->three_cate_id)['name'];
            $catename = $one.$three;
            $v['cate_name'] = $catename;

            $day_order = 0;
            if($v['order_num']>0){
                $day_order = round($v['order_num']/$hday,2);
            }

            $v['day_order'] =  $day_order;

            $fba_inventory = $v['in_stock_num']+$v['in_bound_num']+$v['transfer_num'];

            $fba_inventory_day = 0;

            if($fba_inventory>0&&$day_order>0){
                $fba_inventory_day =  ceil($fba_inventory/$day_order);
            }

             $v['fba_inventory_day'] = $fba_inventory_day;
             $v['time'] = date('m.d',strtotime($start_time)).'~'.date('m.d',strtotime($end_time));

             $v['fasin_codes'] = implode(',',$v['fasin_code'])??'';
             $v['type_name'] = '';
             if($v['type']==1){$v['type_name']='利润';} if($v['type']==2){$v['type_name']='霸链';} if($v['type']==3){$v['type_name']='冲量';} if($v['type']==4){$v['type_name']='清仓退货';}
             $v['strategys'] =  implode(',',array_column($v['core_word'],'strategy'))??'';
             $v['core_words'] =  implode(',',array_column($v['core_word'],'core_words'))??'';
             $v['shops_name'] = implode(',',$v['shops'])??'';
             $v['shops_fzs'] = implode(',',$v['shops_fz'])??'';
             $v['shops_fzs_all'] = implode(',',$v['shops_fz_all'])??'';
             $v['total_inventory'] = $v['transfer_num']+$v['in_stock_num']+$v['in_bound_num'];


            //转化率 = 销量/总会话量
            $v['conversion_rate'] = 0;

            $sessions = 0;
            if(isset($sessions_total[$v['fasin']])){
                $sessions = $sessions_total[$v['fasin']];
            }

            if($sessions>0&&$v['sales_num']>0){
                $v['conversion_rate'] = round(($v['sales_num']/$sessions)*100,2);
            }

        }

        $fasin_res = array_values($fasin_res);

        $posttype = $params['posttype']??1;
        //fasin_codes
        //type_name
        //strategys = core_word[0]['strategy']
        //shops_name = shops
        //shops_fzs
        //shops_fzs_all
        //total_inventory=transfer_num+in_stock_num+in_bound_num
        //core_words = core_word[0]['core_word']
        if($posttype==2){
            $p['title']='fasin数据报表'.time();
            $p['title_list']  = [
                'fasin'=>'父asin',
                'fasin_codes'=>'链接代号',
                'all_rank'=>'总排名',
                'cate_rank'=>'分类排名',
                'type_name'=>'链接定位',
                'strategys'=>'策略',
                'shops_name'=>'店铺',
                'shops_fzs'=>'店铺负责人',
                'cate_name'=>'类目',
                'shops_fzs_all'=>'店铺总负责人',
                'user'=>'负责人',
                'time'=>'日期',
                'sales_price'=>'总销售额',
                'sales_num'=>'销量',
                'day_order'=>'日销',
                'week_total_flow'=>'总流量',
                'ad_budget'=>'广告预算',
                'ad_price'=>'广告实际花费',
                'ad_sales'=>'广告销售额',
                'acos'=>'ACOS',
                'tacos'=>'TACOS',
                'fba_inventory_day'=>'周转天数',
                'return_num'=>'退货数量',
                'return_rate'=>'退货率',
                'total_inventory'=>'库存情况（可售+预留+在途）',
                'core_words'=>'核心词',
            ];

            // $this->excel_expord($p);
            
            $p['data'] =   $fasin_res;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = 'fasin数据报表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return $this->FailBack('加入队列失败');
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }

        return ['data' => $fasin_res,'totalnum' => $totalnum];
    }




    //fasin数据报表-店铺
    public function DatawholeFasinByShop($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $start_time = date('Y-m-d',time());
        $end_time = date('Y-m-d 23:59:59',time());

        if (isset($params['start_time'])) {
            $start_time = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end_time = $params['end_time'].' 23:59:59';
        }

        $shop_list = Db::table('amazon_fasin')->get();

        $shops = [];

        foreach ($shop_list as $v) {
            # code...
            $shop_id = explode(',', $v->shops);
            $shops = array_merge($shops,$shop_id);
        }
        $shops = array_filter(array_unique($shops)); 
        $shops = array_values($shops); 

        
        $list =  db::table('shop')->whereIn('Id',$shops);

        //负责人 总负责人搜索

        if(isset($params['shops_fz'])){
            $user_fz = $params['shops_fz'];
            $list =  $list->whereRaw("find_in_set({$user_fz},`user_fz`)");
        }

        if(isset($params['shops_fz_all'])){
            $user_fz_all = $params['shops_fz_all'];
            $list =  $list->where('user_fz_all',$user_fz_all);
        }

               
        $totalnum = $list->count();
        $list = $list->offset($pagenNum)->limit($limit)->select('Id','shop_name','user_fz','user_fz_all')->get();


        $day_report = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->whereBetween('b.ds', [$start_time, $end_time])->select('a.*','b.ds')->get();

        $day_ary = [];
        foreach ($day_report as $v) {
            # code...
            $key = $v->shop_id;

            if(isset($day_ary[$key]['sales_num'])){
                $day_ary[$key]['sales_num']+= round($v->sales_num,2);
            }else{
                $day_ary[$key]['sales_num'] = round($v->sales_num,2);
            }

            if(isset($day_ary[$key]['sales_price'])){
                $day_ary[$key]['sales_price']+= round($v->sales_price,2);
            }else{
                $day_ary[$key]['sales_price'] = round($v->sales_price,2);
            }


            if(isset($day_ary[$key]['ad_price'])){
                $day_ary[$key]['ad_price']+= round($v->ad_price,2);
            }else{
                $day_ary[$key]['ad_price'] = round($v->ad_price,2);
            }

            if(isset($day_ary[$key]['ad_sales'])){
                $day_ary[$key]['ad_sales']+= round($v->ad_sales,2);
            }else{
                $day_ary[$key]['ad_sales'] = round($v->ad_sales,2);
            }

            if(isset($day_ary[$key]['fba_inventory'])){
                $day_ary[$key]['fba_inventory']+= round($v->fba_inventory,2);
            }else{
                $day_ary[$key]['fba_inventory'] = round($v->fba_inventory,2);
            }

            if(isset($day_ary[$key]['ad_num'])){
                $day_ary[$key]['ad_num']+= round($v->ad_num,2);
            }else{
                $day_ary[$key]['ad_num'] = round($v->ad_num,2);
            }

            $day_ary[$key]['data'][]= $v;
        }

        foreach ($day_ary as $key => $value) {
            $day_ary[$key]['sales_num'] = round($value['sales_num'],2);
            $day_ary[$key]['sales_price'] = round($value['sales_price'],2);
            $day_ary[$key]['ad_price'] = round($value['ad_price'],2);
            $day_ary[$key]['ad_sales'] = round($value['ad_sales'],2);
            $day_ary[$key]['fba_inventory'] = round($value['fba_inventory'],2);
            $day_ary[$key]['ad_num'] = round($value['ad_num'],2);
            # code...
        }

        foreach ($list as $v) {
            # code...
            if(isset($day_ary[$v->Id])){
                $v->data = $day_ary[$v->Id];
            }
            $vshops_fz = [];
            if(!empty($v->user_fz)){
                $user_fz_ids = explode(',',$v->user_fz);
                foreach ($user_fz_ids as $fz_id) {
                    # code...
                    if($fz_id>0){
                        $vshops_fz[] = $this->GetUsers($fz_id)['account'];
                    }
                }

            }
            $v->user_fz = implode(',',$vshops_fz);
          
            if($v->user_fz_all>0){
                $v->user_fz_all = $this->GetUsers($v->user_fz_all)['account'];
            }else{
                $v->user_fz_all = '';
            }

        }


        return ['data' => $list,'totalnum' => $totalnum];


        // $shop_id = 0;

        // if(isset($params['shop_id'])){
        //     $shop_id = $params['shop_id'];
        //     $list = $list->whereRaw("find_in_set({$shop_id},`shops`)");
        // }

        // //负责人 总负责人搜索
        // $shop_model = db::table('shop');

        // $is_shop = false;
        // if(isset($params['shops_fz'])){
        //     $user_fz = $params['shops_fz'];
        //     $is_shop = true;
        //     $shop_model =  $shop_model->whereRaw("find_in_set({$user_fz},`user_fz`)");
        // }

        // if(isset($params['shops_fz_all'])){
        //     $user_fz_all = $params['shops_fz_all'];
        //     $is_shop = true;
        //     $shop_model =  $shop_model->where('user_fz_all',$user_fz_all);
        // }

        // if($is_shop){
        //     $shop_res =  $shop_model->get()->toArray();
        //     $shop_ids = array_column($shop_res,'Id');
        //     // var_dump($shop_ids);
        //     foreach ($shop_ids  as $k => $sid) {
        //         # code...
        //         if ($k==0){
        //             $list = $list->orwhereRaw("find_in_set({$sid},`shops`)");
        //         }else{
        //             $list = $list->orwhereRaw("find_in_set({$sid},`shops`)");
        //         }
                
        //     }
    
        // }
       

        // $list = $list->where('is_self',1);
       
        // $totalnum = $list->grouby('')->get()->count();
        // $list = $list->offset($pagenNum)->limit($limit)->get();



        // $day_report = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->whereBetween('b.ds', [$start_time, $end_time])->select('a.*')->get();

        // $day_ary = [];
        // foreach ($day_report as $v) {
        //     # code...
        //     $key = $v->shop_id.$v->fasin;
        //     $day_ary[$key] = $v;
        // }

//         return ['data' => $fasin_res,'totalnum' => $totalnum];
    }



    //fasin预算导入
    public function ImportFasinPlan($params){
        $p['row'] = ['fasin','year','season','shop_id','is_new','role','cost_price','return_rate','month_sales1','month_sales2','month_sales3','month_sales4','month_sales5','month_sales6','month_sales7','month_sales8','month_sales9','month_sales10','month_sales11','month_sales12','month_price1','month_price2','month_price3','month_price4','month_price5','month_price6','month_price7','month_price8','month_price9','month_price10','month_price11','month_price12','ad_spend1','ad_spend2','ad_spend3','ad_spend4','ad_spend5','ad_spend6','ad_spend7','ad_spend8','ad_spend9','ad_spend10','ad_spend11','ad_spend12','handling_rate','other_rate','fba_rate','fba_inventory_price','dec_price','freight','warehouse_labor_costs','other_operate'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);
        db::beginTransaction(); 
        foreach ($data as $v) {
            # code...
            if(!empty($v['fasin'])){
                try {
                    //code...
                    $this->SaveFasinPlanM($v);
                } catch (\Throwable $th) {
                    //throw $th;
                    db::rollback();// 回调
                    return ['type'=>'fail','msg'=>$th->getMessage()];
                }
            }
        }
        db::commit();
      
        return ['msg'=>'导入成功','type'=>'success'];
    }


    //fasin款号预算导入
    public function ImportFasinCusPlan($params){
        $p['row'] = ['custom_sku','1','2','3','4','5','6','7','8','9','10','11','12'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);

        $newdatas = [];

        foreach ($data as $v) {
            # code...
            $cus_res = db::table('self_custom_sku')->where('custom_sku',$v['custom_sku'])->orwhere('old_custom_sku',$v['custom_sku'])->first();
            if(!$cus_res){
                return ['type'=>'fail','msg'=>'无此库存sku'.$v['custom_sku']];
            }
            for ($i=1; $i < 13; $i++) { 
                # code...
                if($v[$i]>0){
                    $newdata['spu'] = $cus_res->spu;
                    $newdata['spu_id'] = $cus_res->spu_id;
                    $newdata['color'] = $cus_res->color;
                    $newdata['size'] = $cus_res->size;
                    $newdata['color_name'] =db::table('self_color_size')->where('identifying',$cus_res->color)->first()->name??'';
                    $newdata['fasin_code'] = $params['fasin_code'];
                    $newdata['num'] = $v[$i];
                    $newdata['user_id'] = $params['user_id'];
                    $newdata['moon'] = $i;
                    $newdatas[] = $newdata;
                }

            }
          
        }



        // var_dump( $newdata);

        db::beginTransaction(); 
        foreach ($newdatas as $v) {
            # code...
            try {
                //code...
                $a = $this->SaveFasinCusPlanM($v);
            } catch (\Throwable $th) {
                //throw $th;
                db::rollback();// 回调
                return ['type'=>'fail','msg'=>$th->getLine().'--'.$th->getMessage()];
            }

            if($a['type']=='fail'){
                db::rollback();
                return ['type'=>'fail','msg'=>$a['msg']];
            }
            
        }
        db::commit();
        
        return ['msg'=>'导入成功','type'=>'success'];
    }

//   `is_new`  '新老品 0老 1新',
//   `role` '角色',
//   `cost_price`  '成本单价',
//   `return_rate`  '退货率',
//   `month_sales1`  '月销',
//   `month_price1`  '月均价',
//   `ad_spend1`  '广告花费',
//   `handling_rate`  '手续费率',
//   `other_rate`  '其他费用率',
//   `fba_rate` 'fba费用',
//   `fba_inventory_price`  'fba仓储费',
//   `dec_price`  '折扣费',
//   `unline_price`  '线下费用',

//15-20  两个月

    public function SaveFasinPlanM($params){
        $data['fasin'] = $params['fasin'];
        
        if(isset($params['is_new'])){
            $data['is_new'] = $params['is_new'];
        }

        if(isset($params['shop_id'])){
            $data['shop_id'] = $params['shop_id'];
            $fasin_bind = db::table('amazon_fasin_bind')->where('fasin',$data['fasin'])->where('shop_id',$data['shop_id'])->first();
            if(!$fasin_bind ){
                $data['fasin_code'] = $data['fasin'];
            }else{
                $data['fasin_code'] = $fasin_bind->fasin_code;
            }

        }
       
        if(isset($params['role'])){
            $data['role'] = $params['role'];
        }
        if(isset($params['cost_price'])){
            $data['cost_price'] = $params['cost_price'];
        }
        if(isset($params['return_rate'])){
            $data['return_rate'] = round($params['return_rate']/100,2);
        }
        if(isset($params['handling_rate'])){
            $data['handling_rate'] = round($params['handling_rate']/100,2);
        }
        if(isset($params['other_rate'])){
            $data['other_rate'] = round($params['other_rate']/100,2);
        }
        if(isset($params['fba_rate'])){
            $data['fba_rate'] = $params['fba_rate'];
        }
        if(isset($params['fba_inventory_price'])){
            $data['fba_inventory_price'] = round($params['fba_inventory_price']/100,2);
        }
        if(isset($params['dec_price'])){
            $data['dec_price'] = round($params['dec_price']/100,2);
        }
        if(isset($params['unline_price'])){
            $data['unline_price'] =  round($params['unline_price']/100,2);
        }

        if(isset($params['month_sales1'])){
            $data['month_sales1'] = $params['month_sales1'];
        }
        if(isset($params['month_sales2'])){
            $data['month_sales2'] = $params['month_sales2'];
        }
        if(isset($params['month_sales3'])){
            $data['month_sales3'] = $params['month_sales3'];
        }
        if(isset($params['month_sales4'])){
            $data['month_sales4'] = $params['month_sales4'];
        }
        if(isset($params['month_sales5'])){
            $data['month_sales5'] = $params['month_sales5'];
        }
        if(isset($params['month_sales6'])){
            $data['month_sales6'] = $params['month_sales6'];
        }
        if(isset($params['month_sales7'])){
            $data['month_sales7'] = $params['month_sales7'];
        }
        if(isset($params['month_sales8'])){
            $data['month_sales8'] = $params['month_sales8'];
        }
        if(isset($params['month_sales9'])){
            $data['month_sales9'] = $params['month_sales9'];
        }
        if(isset($params['month_sales10'])){
            $data['month_sales10'] = $params['month_sales10'];
        }
        if(isset($params['month_sales11'])){
            $data['month_sales11'] = $params['month_sales11'];
        }
        if(isset($params['month_sales12'])){
            $data['month_sales12'] = $params['month_sales12'];
        }

        if(isset($params['month_price1'])){
            $data['month_price1'] = $params['month_price1'];
        }
        if(isset($params['month_price2'])){
            $data['month_price2'] = $params['month_price2'];
        }
        if(isset($params['month_price3'])){
            $data['month_price3'] = $params['month_price3'];
        }
        if(isset($params['month_price4'])){
            $data['month_price4'] = $params['month_price4'];
        }
        if(isset($params['month_price5'])){
            $data['month_price5'] = $params['month_price5'];
        }
        if(isset($params['month_price6'])){
            $data['month_price6'] = $params['month_price6'];
        }
        if(isset($params['month_price7'])){
            $data['month_price7'] = $params['month_price7'];
        }
        if(isset($params['month_price8'])){
            $data['month_price8'] = $params['month_price8'];
        }
        if(isset($params['month_price9'])){
            $data['month_price9'] = $params['month_price9'];
        }
        if(isset($params['month_price10'])){
            $data['month_price10'] = $params['month_price10'];
        }
        if(isset($params['month_price11'])){
            $data['month_price11'] = $params['month_price11'];
        }
        if(isset($params['month_price12'])){
            $data['month_price12'] = $params['month_price12'];
        }

        if(isset($params['ad_spend1'])){
            $data['ad_spend1'] = round($params['ad_spend1']/100,2);
        }
        if(isset($params['ad_spend2'])){
            $data['ad_spend2'] = round($params['ad_spend2']/100,2);
        }
        if(isset($params['ad_spend3'])){
            $data['ad_spend3'] = round($params['ad_spend3']/100,2);
        }
        if(isset($params['ad_spend4'])){
            $data['ad_spend4'] = round($params['ad_spend4']/100,2);
        }
        if(isset($params['ad_spend5'])){
            $data['ad_spend5'] = round($params['ad_spend5']/100,2);
        }
        if(isset($params['ad_spend6'])){
            $data['ad_spend6'] = round($params['ad_spend6']/100,2);
        }
        if(isset($params['ad_spend7'])){
            $data['ad_spend7'] = round($params['ad_spend7']/100,2);
        }
        if(isset($params['ad_spend8'])){
            $data['ad_spend8'] = round($params['ad_spend8']/100,2);
        }
        if(isset($params['ad_spend9'])){
            $data['ad_spend9'] = round($params['ad_spend9']/100,2);
        }
        if(isset($params['ad_spend10'])){
            $data['ad_spend10'] = round($params['ad_spend10']/100,2);
        }
        if(isset($params['ad_spend11'])){
            $data['ad_spend11'] = round($params['ad_spend11']/100,2);
        }
        if(isset($params['ad_spend12'])){
            $data['ad_spend12'] = round($params['ad_spend12']/100,2);
        }

        $data['year'] = $params['year']??date('Y',time());
        $data['season'] = $params['season'];

        if(isset($params['freight'])){
            $data['freight'] = $params['freight'];
        }

        
        if(isset($params['warehouse_labor_costs'])){
            $data['warehouse_labor_costs'] = $params['warehouse_labor_costs'];
        }

        
        if(isset($params['other_operate'])){
            $data['other_operate'] = $params['other_operate'];
        }


        $is_repeat = db::table('amazon_fasin_plan_info')->where('fasin',$data['fasin'])->first();
        if($is_repeat){
            db::table('amazon_fasin_plan_info')->where('fasin',$data['fasin'])->update($data);
        }else{
            db::table('amazon_fasin_plan_info')->insert($data);
        }
        return ['type'=>'success','msg'=>'添加成功'];

    }

    public function  GetFasinPlanOtherM($params){
        $type = $params['type'];

        switch ($type) {
            case '1':
                //部门
                # code...
                $res = $this->GetFasinPlanOrganizesM($params)['data'];
                break;
            case '2':
                //人员
            # code...
                $list = Db::table('amazon_fasin_plan_info as a')->leftjoin('amazon_fasin as b','a.fasin','=','b.fasin')->groupby('b.user_id')->where('user_id','>',0)->get()->toarray();
                $res = [];
                foreach ($list as $v) {
                    # code...
                    $o['name'] = $this->GetUsers($v->user_id)['account'];
                    $o['data'] = $this->GetFasinSalePlanM(['user_id'=>[$v->user_id],'year'=>$params['year']]);
                    $res[] = $o;
                }
                break;
            case '3':
                //品类
            # code...
                $list = Db::table('amazon_fasin_plan_info as a')->leftjoin('amazon_fasin as b','a.fasin','=','b.fasin')->groupby('b.one_cate_id')->select(db::raw('group_concat(a.fasin) as fasins'),'b.one_cate_id')->where('b.one_cate_id','>',0)->get()->toarray();
                $res = [];
                foreach ($list as $v) {
                    # code...
                    $o['name'] = $this->GetCategory($v->one_cate_id)['name'];
                    $fasins = explode(',',$v->fasins);
                    $o['data'] = $this->GetFasinSalePlanM(['fasin'=>$fasins,'year'=>$params['year']]);
                    $res[] = $o;
                }
                break;
            case '4':
                //季节
                # code...
                $list = Db::table('amazon_fasin_plan_info as a')->leftjoin('amazon_fasin as b','a.fasin','=','b.fasin')->groupby('a.season')->select(db::raw('group_concat(a.fasin) as fasins'),'a.season')->get()->toarray();
                $res = [];
                foreach ($list as $v) {
                    # code...
                    if($v->season==1){
                        $o['name'] = '夏季';
                    }
                    if($v->season==2){
                        $o['name'] = '冬季';
                    }
                    if($v->season==3){
                        $o['name'] = '四季';
                    }
                    
                    $fasins = explode(',',$v->fasins);
                    $o['data'] = $this->GetFasinSalePlanM(['fasin'=>$fasins,'year'=>$params['year']]);
                    $res[] = $o;
                }
                break;
            case '5':
                //店铺
                # code...
                $list = Db::table('amazon_fasin_plan_info')->groupby('shop_id')->select(db::raw('group_concat(fasin) as fasins'),'shop_id')->get();
                $res = [];
                foreach ($list as $v) {
                    # code...
                    $o['name'] = $this->GetShop($v->shop_id)['shop_name'];
                    $fasins = explode(',',$v->fasins);
                    $o['data'] = $this->GetFasinSalePlanM(['fasin'=>$fasins,'year'=>$params['year']]);
                    $res[] = $o;
                }
                break;
            case '6':
                //国家
                $list = Db::table('amazon_fasin_plan_info')->groupby('shop_id')->select('shop_id')->get()->toarray();
                $shop_ids = array_column($list,'shop_id');
                $shop = db::table('shop')->whereIn('Id',$shop_ids)->get()->toarray();
                $res = [];
                $contrys = [];
                foreach ($shop as $sv) {
                    # code...
                    $contrys[$sv->country_id][] = $sv->Id;
                }

                foreach ($contrys as $k=>$v) {
                    # code...
                    $o['name'] = db::table('countrys')->where('Id',$k)->first()->name;
                    $o['data'] = $this->GetFasinSalePlanM(['shop_id'=>$v,'year'=>$params['year']]);
                    $res[] = $o;
                }
                break;
                
        }

        return $res;

    }

    public function  GetFasinPlanOrganizesM($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $year = $params['year'];

        // $amazon_organizes = [19,25,26,27];
        $amazon_organizes = [27,28,29,30,31,32];
        $o_arr = [];
        foreach ($amazon_organizes as $v) {
            # code...
            $name =  db::table('organizes')->where('id', $v)->first();
            $o = db::table('organizes')->where('id', $v)->orwhere('fid',$v)->get()->toarray();
            $one['name'] = $name ->name??'';
            $one['ids'] = array_column( $o,'Id');
            $o_arr[] = $one;
        }


        $data = [];
        foreach ($o_arr as $v) {
            $organizes_member = db::table('organizes_member')->whereIn('organize_id',$v['ids'])->get()->toarray();
            $user_ids = array_column($organizes_member,'user_id');
            $ones['name'] = $v['name'];
            $ones['data'] = $this->GetFasinSalePlanM(['user_id'=>$user_ids,'year'=>$year]);
            $data[] = $ones;

        }

        return ['data' => $data,'totalnum' => count($o_arr)];

    }


    public function GetFasinSalesM($params){
        $year = $params['year']??date('Y',time());
        $data = [];
        for ($i=1; $i < 13; $i++) { 
            # code...
            if($i<10){
                $ie = $i+1;
                $start_time = $year.'-0'.$i.'-01 00:00:00';
                $end_time = $year.'-0'.$ie.'-01 23:59:59';
            }elseif($i==12){
                $start_time = $year.'-'.$i.'-01 00:00:00';
                $end_time = $year.'-'.$i.'-31 23:59:59';
            }else{
                $ie = $i+1;
                $start_time = $year.'-'.$i.'-01 00:00:00';
                $end_time = $year.'-'.$ie.'-01 23:59:59';
            }

            $list = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->whereBetween('b.ds', [$start_time, $end_time])->where('a.status',1)->select(db::raw('IFNULL(sum(a.sales_num),0) as sales_num'));
                 
            if(isset($params['fasin'])){
                $list = $list->whereIn('a.fasin',$params['fasin']);
            }

            if(isset($params['user_id'])){
                $list = $list->whereIn('b.user_id',$params['user_id']);
            }

            if(isset($params['shop_id'])){
                $list = $list->whereIn('a.shop_id',$params['shop_id']);
            }

            $list = $list->first();
            $data[$i] = 0;
            if($list){
                $data[$i] = $list->sales_num;
            }
           
        }



        return $data;

    }

    public function GetFasinSalePlanM($params){
        $year = $params['year']??date('Y',time());
        $list = Db::table('amazon_fasin_plan_info as b')->leftjoin('amazon_fasin as a','a.fasin','=','b.fasin')->where('b.year',$year)->select(db::raw('IFNULL(sum(b.month_sales1),0) as month_sales1'),db::raw('IFNULL(sum(b.month_sales2),0) as month_sales2'),db::raw('IFNULL(sum(b.month_sales3),0) as month_sales3'),db::raw('IFNULL(sum(b.month_sales4),0) as month_sales4'),db::raw('IFNULL(sum(b.month_sales5),0) as month_sales5'),db::raw('IFNULL(sum(b.month_sales6),0) as month_sales6'),db::raw('IFNULL(sum(b.month_sales7),0) as month_sales7'),db::raw('IFNULL(sum(b.month_sales8),0) as month_sales8'),db::raw('IFNULL(sum(b.month_sales9),0) as month_sales9'),db::raw('IFNULL(sum(b.month_sales10),0) as month_sales10'),db::raw('IFNULL(sum(b.month_sales11),0) as month_sales11'),db::raw('IFNULL(sum(b.month_sales12),0) as month_sales12'));
        if(isset($params['fasin'])){
            $list = $list->whereIn('b.fasin',$params['fasin']);
        }

        if(isset($params['user_id'])){
            $list = $list->whereIn('a.user_id',$params['user_id']);
        }
        if(isset($params['shop_id'])){
            $list = $list->whereIn('b.shop_id',$params['shop_id']);
        }

        $list = $list->first();

        //查询实际销量
        $now = $this->GetFasinSalesM($params);

        $new_data = [];

        $i=1;
        foreach ($now as $v) {
            # code...
            $d['now'] = $v;
            $k = 'month_sales'.$i;
            $d['plan'] = $list->$k;
            $d['rate'] = 0;
            if($d['now']>0&&$d['plan']>0){
                $d['rate'] = round($d['now']/$d['plan']*100,2);
            }
            $d['moon'] = $i;
           
            $new_data[] = $d;
            $i++;
        }
        
        return $new_data;
    }
    

    //审核预算
    public function FasinPlanExamine($params){
       $user_id = $params['user_id'];
       $is_examine = $params['is_examine'];
       $id = $params['id'];
       db::table('amazon_fasin_plan_info')->where('id',$id)->update(['examine_user'=>$user_id,'is_examine'=>$is_examine]);
       return ['type'=>'success','msg'=>'修改成功'];
    }

    public function GetFasinPlanM($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        
        // $year = $params['year']??date('Y',time());

        $list = Db::table('amazon_fasin_plan_info as b')->leftjoin('amazon_fasin as a','a.fasin','=','b.fasin')->select('b.*','a.*','b.id','b.fasin');

       
        
        if(isset($params['year'])){
            $list = $list->where('b.year',$params['year']);
        }

        if(isset($params['fasin'])){
            $list = $list->where('b.fasin',$params['fasin']);
        }

        if(isset($params['one_cate_id'])){
            $list =  $list->whereIn('a.one_cate_id',$params['one_cate_id']);
        }

        if(isset($params['two_cate_id'])){
            $list =  $list->whereIn('a.two_cate_id',$params['two_cate_id']);
        }

        if(isset($params['three_cate_id'])){
            $list =  $list->whereIn('a.three_cate_id',$params['three_cate_id']);
        }


        if(isset($params['user_id'])){
            $list = $list->where('a.user_id',$params['user_id']);
        }
        
        if(isset($params['season'])){
            $list = $list->where('b.season',$params['season']);
        }

        if(isset($params['shop_id'])){
            $list = $list->where('b.shop_id',$params['shop_id']);
        }
        if(isset($params['is_new'])){
            $list = $list->where('b.is_new',$params['is_new']);
        }

        
        if(isset($params['organizes_id'])){
            $rganizes_res = db::table('organizes')->where('id',$params['organizes_id'])->orwhere('fid',$params['organizes_id'])->get()->toarray();
            $rganizes_ids = array_column($rganizes_res,'Id');
            $list = $list->leftjoin('organizes_member as om','a.user_id','=','om.user_id')->whereIn('om.organize_id',$rganizes_ids);
        }

        
        if(isset($params['country_id'])){
            $list = $list->leftjoin('shop as sp','b.shop_id','=','sp.Id')->leftjoin('countrys as cs','sp.country_id','=','cs.Id')->where('cs.Id',$params['country_id']);
        }


        // if(isset($params['group'])){
        //     $list = $list->groupby($params['group']);
        // }


        $totalnum = $list->count();
        $list = $list->offset($pagenNum)->limit($limit)->get();


        foreach ($list as $v) {
            # code...
            $one = $this->GetCategory($v->one_cate_id)['name'];
            $three = $this->GetCategory($v->three_cate_id)['name'];
            $catename = $one.$three;
            $v->cate_name = $catename;
            $v->user = $this->GetUsers($v->user_id)['account'];
            $shops = $this->GetShop($v->shop_id);
            $v->shop_name = $shops['shop_name'];

            //国家
            $v->country = '';
            $country_id = $shops['country_id'];
            $v->country = db::table('countrys')->where('Id',$country_id)->first()->name??'';

            //部门
            $v->organizes = '';
            $organizes_member = db::table('organizes_member')->where('user_id',$v->user_id)->first();
            if($organizes_member){
                $organizes_res = db::table('organizes')->where('id',$organizes_member->organize_id)->first();
                if(!$organizes_res){
                    $v->organizes = '';
                }else{
                    if($organizes_res->type==1){
                        $v->organizes = $organizes_res->name;
                    }else{
                        $organizes_ress = db::table('organizes')->where('id',$organizes_res->fid)->first();
                        $v->organizes = $organizes_ress->name;
                    }
                }

            }
           

            //均价
            $v->total_avg_price = 0;
            $v->total_avg_price = round(($v->month_price1+$v->month_price2+$v->month_price3+$v->month_price4+$v->month_price5+$v->month_price6+$v->month_price7+$v->month_price8+$v->month_price9+$v->month_price10+$v->month_price11+$v->month_price12)/12,2);
            //合计数
            $v->total_count  = 0;
            $v->total_count = $v->month_sales1+$v->month_sales2+$v->month_sales3+$v->month_sales4+$v->month_sales5+$v->month_sales6+$v->month_sales7+$v->month_sales8+$v->month_sales9+$v->month_sales10+$v->month_sales11+$v->month_sales12;
          
            //fba库存
            $v->fba_inventory_num = 0;
            $skus = db::table('self_sku')->where('fasin',$v->fasin)->get()->toarray();
            $sku_ids = array_column($skus,'id');
            $product = db::table('product_detail')->whereIn('sku_id',$sku_ids)->select(db::raw('IFNULL(sum(in_stock_num),0) as in_stock_num'),db::raw('IFNULL(sum(in_bound_num),0) as in_bound_num'),db::raw('IFNULL(sum(transfer_num),0) as transfer_num'))->first();

            if($product){
                $v->fba_inventory_num = $product->in_stock_num +$product->in_bound_num+$product->transfer_num;
            }
            

            //汇率
            $v->exchange_rate = 8; 
            //销售收入 = 汇率*月销*月均价
            $sales_revenue['sales_revenue1'] = ceil($v->exchange_rate*$v->month_sales1*$v->month_price1);
            $sales_revenue['sales_revenue2'] = ceil($v->exchange_rate*$v->month_sales2*$v->month_price2);
            $sales_revenue['sales_revenue3'] = ceil($v->exchange_rate*$v->month_sales3*$v->month_price3);
            $sales_revenue['sales_revenue4'] = ceil($v->exchange_rate*$v->month_sales4*$v->month_price4);
            $sales_revenue['sales_revenue5'] = ceil($v->exchange_rate*$v->month_sales5*$v->month_price5);
            $sales_revenue['sales_revenue6'] = ceil($v->exchange_rate*$v->month_sales6*$v->month_price6);
            $sales_revenue['sales_revenue7'] = ceil($v->exchange_rate*$v->month_sales7*$v->month_price7);
            $sales_revenue['sales_revenue8'] = ceil($v->exchange_rate*$v->month_sales8*$v->month_price8);
            $sales_revenue['sales_revenue9'] = ceil($v->exchange_rate*$v->month_sales9*$v->month_price9);
            $sales_revenue['sales_revenue10'] = ceil($v->exchange_rate*$v->month_sales10*$v->month_price10);
            $sales_revenue['sales_revenue11'] = ceil($v->exchange_rate*$v->month_sales11*$v->month_price11);
            $sales_revenue['sales_revenue12'] = ceil($v->exchange_rate*$v->month_sales12*$v->month_price12);
            $v->sales_revenu = $sales_revenue;

            //合计收入
            $v->total_income = 0;
            $v->total_income = array_sum($sales_revenue);


            //销售成本 = 月销*单价
            $cost_of_sales['cost_of_sales1'] = ceil($v->month_sales1*$v->cost_price);
            $cost_of_sales['cost_of_sales2'] = ceil($v->month_sales2*$v->cost_price);
            $cost_of_sales['cost_of_sales3'] = ceil($v->month_sales3*$v->cost_price);
            $cost_of_sales['cost_of_sales4'] = ceil($v->month_sales4*$v->cost_price);
            $cost_of_sales['cost_of_sales5'] = ceil($v->month_sales5*$v->cost_price);
            $cost_of_sales['cost_of_sales6'] = ceil($v->month_sales6*$v->cost_price);
            $cost_of_sales['cost_of_sales7'] = ceil($v->month_sales7*$v->cost_price);
            $cost_of_sales['cost_of_sales8'] = ceil($v->month_sales8*$v->cost_price);
            $cost_of_sales['cost_of_sales9'] = ceil($v->month_sales9*$v->cost_price);
            $cost_of_sales['cost_of_sales10'] = ceil($v->month_sales10*$v->cost_price);
            $cost_of_sales['cost_of_sales11'] = ceil($v->month_sales11*$v->cost_price);
            $cost_of_sales['cost_of_sales12'] = ceil($v->month_sales12*$v->cost_price);
            $v->cost_of_sales = $cost_of_sales;

            //净销售数量 =  月销*（1-退货率）
            $net_sales['net_sales1'] = ceil($v->month_sales1*(1-$v->return_rate));
            $net_sales['net_sales2'] = ceil($v->month_sales2*(1-$v->return_rate));
            $net_sales['net_sales3'] = ceil($v->month_sales3*(1-$v->return_rate));
            $net_sales['net_sales4'] = ceil($v->month_sales4*(1-$v->return_rate));
            $net_sales['net_sales5'] = ceil($v->month_sales5*(1-$v->return_rate));
            $net_sales['net_sales6'] = ceil($v->month_sales6*(1-$v->return_rate));
            $net_sales['net_sales7'] = ceil($v->month_sales7*(1-$v->return_rate));
            $net_sales['net_sales8'] = ceil($v->month_sales8*(1-$v->return_rate));
            $net_sales['net_sales9'] = ceil($v->month_sales9*(1-$v->return_rate));
            $net_sales['net_sales10'] = ceil($v->month_sales10*(1-$v->return_rate));
            $net_sales['net_sales11'] = ceil($v->month_sales11*(1-$v->return_rate));
            $net_sales['net_sales12'] = ceil($v->month_sales12*(1-$v->return_rate));
            $v->net_sales = $net_sales;

            //净销售收入 = 汇率*净月销*月均价
            $net_sales_revenue['net_sales_revenue1'] = ceil($v->exchange_rate*$net_sales['net_sales1']*$v->month_price1);
            $net_sales_revenue['net_sales_revenue2'] = ceil($v->exchange_rate*$net_sales['net_sales2']*$v->month_price2);
            $net_sales_revenue['net_sales_revenue3'] = ceil($v->exchange_rate*$net_sales['net_sales3']*$v->month_price3);
            $net_sales_revenue['net_sales_revenue4'] = ceil($v->exchange_rate*$net_sales['net_sales4']*$v->month_price4);
            $net_sales_revenue['net_sales_revenue5'] = ceil($v->exchange_rate*$net_sales['net_sales5']*$v->month_price5);
            $net_sales_revenue['net_sales_revenue6'] = ceil($v->exchange_rate*$net_sales['net_sales6']*$v->month_price6);
            $net_sales_revenue['net_sales_revenue7'] = ceil($v->exchange_rate*$net_sales['net_sales7']*$v->month_price7);
            $net_sales_revenue['net_sales_revenue8'] = ceil($v->exchange_rate*$net_sales['net_sales8']*$v->month_price8);
            $net_sales_revenue['net_sales_revenue9'] = ceil($v->exchange_rate*$net_sales['net_sales9']*$v->month_price9);
            $net_sales_revenue['net_sales_revenue10'] = ceil($v->exchange_rate*$net_sales['net_sales10']*$v->month_price10);
            $net_sales_revenue['net_sales_revenue11'] = ceil($v->exchange_rate*$net_sales['net_sales11']*$v->month_price11);
            $net_sales_revenue['net_sales_revenue12'] = ceil($v->exchange_rate*$net_sales['net_sales12']*$v->month_price12);
            $v->net_sales_revenue = $net_sales_revenue;


            //净销售成本 = 净销售数量 * 汇率 * 单价
            $net_cost_of_sales['net_cost_of_sales1'] = ceil($net_sales['net_sales1']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales2'] = ceil($net_sales['net_sales2']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales3'] =ceil($net_sales['net_sales3']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales4'] = ceil($net_sales['net_sales4']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales5'] = ceil($net_sales['net_sales5']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales6'] = ceil($net_sales['net_sales6']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales7'] = ceil($net_sales['net_sales7']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales8'] = ceil($net_sales['net_sales8']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales9'] = ceil($net_sales['net_sales9']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales10'] = ceil($net_sales['net_sales10']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales11'] = ceil($net_sales['net_sales11']*$v->cost_price);
            $net_cost_of_sales['net_cost_of_sales12'] = ceil($net_sales['net_sales12']*$v->cost_price);
            $v->net_cost_of_sales = $net_cost_of_sales;

            //手续费 =手续费率 * 净销售收入
            $handling['handling1'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue1']);
            $handling['handling2'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue2']);
            $handling['handling3'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue3']);
            $handling['handling4'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue4']);
            $handling['handling5'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue5']);
            $handling['handling6'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue6']);
            $handling['handling7'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue7']);
            $handling['handling8'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue8']);
            $handling['handling9'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue9']);
            $handling['handling10'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue10']);
            $handling['handling11'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue11']);
            $handling['handling12'] = ceil($v->handling_rate * $net_sales_revenue['net_sales_revenue12']);
            $v->handling = $handling;

            //其他费 =其他费用率 * 净销售收入
            $other['other1'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue1']);
            $other['other2'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue2']);
            $other['other3'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue3']);
            $other['other4'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue4']);
            $other['other5'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue5']);
            $other['other6'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue6']);
            $other['other7'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue7']);
            $other['other8'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue8']);
            $other['other9'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue9']);
            $other['other10'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue10']);
            $other['other11'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue11']);
            $other['other12'] = ceil($v->other_rate * $net_sales_revenue['net_sales_revenue12']);
            $v->other = $other;

         

            //fba配送费用 =单件fba配送费用 * 净销售数量
            $fba['fba1'] = ceil($v->fba_rate*$net_sales['net_sales1']);
            $fba['fba2'] = ceil($v->fba_rate*$net_sales['net_sales2']);
            $fba['fba3'] = ceil($v->fba_rate*$net_sales['net_sales3']);
            $fba['fba4'] = ceil($v->fba_rate*$net_sales['net_sales4']);
            $fba['fba5'] = ceil($v->fba_rate*$net_sales['net_sales5']);
            $fba['fba6'] = ceil($v->fba_rate*$net_sales['net_sales6']);
            $fba['fba7'] = ceil($v->fba_rate*$net_sales['net_sales7']);
            $fba['fba8'] = ceil($v->fba_rate*$net_sales['net_sales8']);
            $fba['fba9'] = ceil($v->fba_rate*$net_sales['net_sales9']);
            $fba['fba10'] = ceil($v->fba_rate*$net_sales['net_sales10']);
            $fba['fba11'] = ceil($v->fba_rate*$net_sales['net_sales11']);
            $fba['fba12'] = ceil($v->fba_rate*$net_sales['net_sales12']);
            $v->fba = $fba;


            //fba仓储费 =fba仓储费率 * 净销售收入
            $fba_inventory['fba_inventory1'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue1']);
            $fba_inventory['fba_inventory2'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue2']);
            $fba_inventory['fba_inventory3'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue3']);
            $fba_inventory['fba_inventory4'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue4']);
            $fba_inventory['fba_inventory5'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue5']);
            $fba_inventory['fba_inventory6'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue6']);
            $fba_inventory['fba_inventory7'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue7']);
            $fba_inventory['fba_inventory8'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue8']);
            $fba_inventory['fba_inventory9'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue9']);
            $fba_inventory['fba_inventory10'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue10']);
            $fba_inventory['fba_inventory11'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue11']);
            $fba_inventory['fba_inventory12'] = ceil($v->fba_inventory_price*$net_sales_revenue['net_sales_revenue12']);
            $v->fba_inventory = $fba_inventory;

            //折扣费 = 折扣费率 * 净销售收入
            $dec['dec1'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue1']);
            $dec['dec2'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue2']);
            $dec['dec3'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue3']);
            $dec['dec4'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue4']);
            $dec['dec5'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue5']);
            $dec['dec6'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue6']);
            $dec['dec7'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue7']);
            $dec['dec8'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue8']);
            $dec['dec9'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue9']);
            $dec['dec10'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue10']);
            $dec['dec11'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue11']);
            $dec['dec12'] = ceil($v->dec_price*$net_sales_revenue['net_sales_revenue12']);
            $v->dec = $dec;

            //线下费率 = 头程运费+仓库人工费+其他运营成本
            $unline_price = $v->freight+$v->warehouse_labor_costs+$v->other_operate;

            //线下费用 = 线下费用率 * 净销售收入
            $unline['unline1'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue1']);
            $unline['unline2'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue2']);
            $unline['unline3'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue3']);
            $unline['unline4'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue4']);
            $unline['unline5'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue5']);
            $unline['unline6'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue6']);
            $unline['unline7'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue7']);
            $unline['unline8'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue8']);
            $unline['unline9'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue9']);
            $unline['unline10'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue10']);
            $unline['unline11'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue11']);
            $unline['unline12'] = ceil($unline_price*$net_sales_revenue['net_sales_revenue12']);
            $v->unline = $unline;

            //广告费 = 广告费率 * 净销售收入
            $ad['ad1'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue1']);
            $ad['ad2'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue2']);
            $ad['ad3'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue3']);
            $ad['ad4'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue4']);
            $ad['ad5'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue5']);
            $ad['ad6'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue6']);
            $ad['ad7'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue7']);
            $ad['ad8'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue8']);
            $ad['ad9'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue9']);
            $ad['ad10'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue10']);
            $ad['ad11'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue11']);
            $ad['ad12'] = ceil($v->ad_spend1*$net_sales_revenue['net_sales_revenue12']);
            $v->ad = $ad;

            //毛利 = 净销售收入 - 净销售成本 - 手续费 - 其他费 - fba配送费用 - fba仓储费 - 折扣费 - 线下费用 - 广告花费
            $gross_profit['gross_profit1'] = $net_sales_revenue['net_sales_revenue1'] - $net_cost_of_sales['net_cost_of_sales1'] - $handling['handling1'] - $other['other1'] - $fba['fba1'] -  $fba_inventory['fba_inventory1'] -  $dec['dec1'] - $unline['unline1']  - $ad['ad1'];
            $gross_profit['gross_profit2'] = $net_sales_revenue['net_sales_revenue2'] - $net_cost_of_sales['net_cost_of_sales2'] - $handling['handling2'] - $other['other2'] - $fba['fba2'] -  $fba_inventory['fba_inventory2'] -  $dec['dec2'] - $unline['unline2']  - $ad['ad2'];
            $gross_profit['gross_profit3'] = $net_sales_revenue['net_sales_revenue3'] - $net_cost_of_sales['net_cost_of_sales3'] - $handling['handling3'] - $other['other3'] - $fba['fba3'] -  $fba_inventory['fba_inventory3'] -  $dec['dec3'] - $unline['unline3']  - $ad['ad3'];
            $gross_profit['gross_profit4'] = $net_sales_revenue['net_sales_revenue4'] - $net_cost_of_sales['net_cost_of_sales4'] - $handling['handling4'] - $other['other4'] - $fba['fba4'] -  $fba_inventory['fba_inventory4'] -  $dec['dec4'] - $unline['unline4']  - $ad['ad4'];
            $gross_profit['gross_profit5'] = $net_sales_revenue['net_sales_revenue5'] - $net_cost_of_sales['net_cost_of_sales5'] - $handling['handling5'] - $other['other5'] - $fba['fba5'] -  $fba_inventory['fba_inventory5'] -  $dec['dec5'] - $unline['unline5']  - $ad['ad5'];
            $gross_profit['gross_profit6'] = $net_sales_revenue['net_sales_revenue6'] - $net_cost_of_sales['net_cost_of_sales6'] - $handling['handling6'] - $other['other6'] - $fba['fba6'] -  $fba_inventory['fba_inventory6'] -  $dec['dec6'] - $unline['unline6']  - $ad['ad6'];
            $gross_profit['gross_profit7'] = $net_sales_revenue['net_sales_revenue7'] - $net_cost_of_sales['net_cost_of_sales7'] - $handling['handling7'] - $other['other7'] - $fba['fba7'] -  $fba_inventory['fba_inventory7'] -  $dec['dec7'] - $unline['unline7']  - $ad['ad7'];
            $gross_profit['gross_profit8'] = $net_sales_revenue['net_sales_revenue8'] - $net_cost_of_sales['net_cost_of_sales8'] - $handling['handling8'] - $other['other8'] - $fba['fba8'] -  $fba_inventory['fba_inventory8'] -  $dec['dec8'] - $unline['unline8']  - $ad['ad8'];
            $gross_profit['gross_profit9'] = $net_sales_revenue['net_sales_revenue9'] - $net_cost_of_sales['net_cost_of_sales9'] - $handling['handling9'] - $other['other9'] - $fba['fba9'] -  $fba_inventory['fba_inventory9'] -  $dec['dec9'] - $unline['unline9']  - $ad['ad9'];
            $gross_profit['gross_profit10'] = $net_sales_revenue['net_sales_revenue10'] - $net_cost_of_sales['net_cost_of_sales10'] - $handling['handling10'] - $other['other10'] - $fba['fba10'] -  $fba_inventory['fba_inventory10'] -  $dec['dec10'] - $unline['unline10']  - $ad['ad10'];
            $gross_profit['gross_profit11'] = $net_sales_revenue['net_sales_revenue11'] - $net_cost_of_sales['net_cost_of_sales11'] - $handling['handling11'] - $other['other11'] - $fba['fba11'] -  $fba_inventory['fba_inventory11'] -  $dec['dec11'] - $unline['unline11']  - $ad['ad11'];
            $gross_profit['gross_profit12'] = $net_sales_revenue['net_sales_revenue12'] - $net_cost_of_sales['net_cost_of_sales12'] - $handling['handling12'] - $other['other12'] - $fba['fba12'] -  $fba_inventory['fba_inventory12'] -  $dec['dec12'] - $unline['unline12']  - $ad['ad12'];
            $v->gross_profit = $gross_profit;


            //毛利率  = 毛利/销售净收入
            $gross_profit_rate['gross_profit_rate1'] = 0;
            $gross_profit_rate['gross_profit_rate2'] = 0;
            $gross_profit_rate['gross_profit_rate3'] = 0;
            $gross_profit_rate['gross_profit_rate4'] = 0;
            $gross_profit_rate['gross_profit_rate5'] = 0;
            $gross_profit_rate['gross_profit_rate6'] = 0;
            $gross_profit_rate['gross_profit_rate7'] = 0;
            $gross_profit_rate['gross_profit_rate8'] = 0;
            $gross_profit_rate['gross_profit_rate9'] = 0;
            $gross_profit_rate['gross_profit_rate10'] =0;
            $gross_profit_rate['gross_profit_rate11'] =0;
            $gross_profit_rate['gross_profit_rate12'] =0;


            if($gross_profit['gross_profit1']>0&&$net_sales_revenue['net_sales_revenue1']>0){
                $gross_profit_rate['gross_profit_rate1'] =  round(($gross_profit['gross_profit1']/$net_sales_revenue['net_sales_revenue1'])*100,2);
            }
            if($gross_profit['gross_profit2']>0&&$net_sales_revenue['net_sales_revenue2']>0){
            $gross_profit_rate['gross_profit_rate2'] =  round(($gross_profit['gross_profit2']/$net_sales_revenue['net_sales_revenue2'])*100,2);
            }
            if($gross_profit['gross_profit3']>0&&$net_sales_revenue['net_sales_revenue3']>0){
            $gross_profit_rate['gross_profit_rate3'] =  round(($gross_profit['gross_profit3']/$net_sales_revenue['net_sales_revenue3'])*100,2);
            }
            if($gross_profit['gross_profit4']>0&&$net_sales_revenue['net_sales_revenue4']>0){
            $gross_profit_rate['gross_profit_rate4'] =  round(($gross_profit['gross_profit4']/$net_sales_revenue['net_sales_revenue4'])*100,2);
            }
            if($gross_profit['gross_profit5']>0&&$net_sales_revenue['net_sales_revenue5']>0){
            $gross_profit_rate['gross_profit_rate5'] =  round(($gross_profit['gross_profit5']/$net_sales_revenue['net_sales_revenue5'])*100,2);
            }
            if($gross_profit['gross_profit6']>0&&$net_sales_revenue['net_sales_revenue6']>0){
            $gross_profit_rate['gross_profit_rate6'] =  round(($gross_profit['gross_profit6']/$net_sales_revenue['net_sales_revenue6'])*100,2);
            }
            if($gross_profit['gross_profit7']>0&&$net_sales_revenue['net_sales_revenue7']>0){
            $gross_profit_rate['gross_profit_rate7'] =  round(($gross_profit['gross_profit7']/$net_sales_revenue['net_sales_revenue7'])*100,2);
            }
            if($gross_profit['gross_profit8']>0&&$net_sales_revenue['net_sales_revenue8']>0){
            $gross_profit_rate['gross_profit_rate8'] =  round(($gross_profit['gross_profit8']/$net_sales_revenue['net_sales_revenue8'])*100,2);
            }
            if($gross_profit['gross_profit9']>0&&$net_sales_revenue['net_sales_revenue9']>0){
            $gross_profit_rate['gross_profit_rate9'] =  round(($gross_profit['gross_profit9']/$net_sales_revenue['net_sales_revenue9'])*100,2);
            }
            if($gross_profit['gross_profit10']>0&&$net_sales_revenue['net_sales_revenue10']>0){
            $gross_profit_rate['gross_profit_rate10'] =  round(($gross_profit['gross_profit10']/$net_sales_revenue['net_sales_revenue10'])*100,2);
            }
            if($gross_profit['gross_profit11']>0&&$net_sales_revenue['net_sales_revenue11']>0){
            $gross_profit_rate['gross_profit_rate11'] =  round(($gross_profit['gross_profit11']/$net_sales_revenue['net_sales_revenue11'])*100,2);
            }
            if($gross_profit['gross_profit12']>0&&$net_sales_revenue['net_sales_revenue12']>0){
            $gross_profit_rate['gross_profit_rate12'] =  round(($gross_profit['gross_profit12']/$net_sales_revenue['net_sales_revenue12'])*100,2);
            }

            $v->gross_profit_rate = $gross_profit_rate;      

            $v->return_rate = $v->return_rate*100;
            $v->handling_rate = $v->handling_rate*100;
            $v->other_rate = $v->other_rate*100;
            $v->fba_inventory_price = $v->fba_inventory_price*100;
            $v->dec_price = $v->dec_price*100;
            $v->unline_price = $v->unline_price*100;
            $v->freight = $v->freight*100;
            $v->warehouse_labor_costs = $v->warehouse_labor_costs*100;
            $v->other_operate = $v->other_operate*100;
            $v->ad_spend1 = $v->ad_spend1*100;
            $v->ad_spend2 = $v->ad_spend2*100;
            $v->ad_spend3 = $v->ad_spend3*100;
            $v->ad_spend4 = $v->ad_spend4*100;
            $v->ad_spend5 = $v->ad_spend5*100;
            $v->ad_spend6 = $v->ad_spend6*100;
            $v->ad_spend7 = $v->ad_spend7*100;
            $v->ad_spend8 = $v->ad_spend8*100;
            $v->ad_spend9 = $v->ad_spend9*100;
            $v->ad_spend10 = $v->ad_spend10*100;
            $v->ad_spend11 = $v->ad_spend11*100;
            $v->ad_spend12 = $v->ad_spend12*100;



            $year = date('Y',time());
            $v->contractData78 = $this->getFasinOrderPlace($v->fasin_code,$year.'-01');
            $v->contractData910 = $this->getFasinOrderPlace($v->fasin_code,$year.'-02');
            $v->contractData1112 = $this->getFasinOrderPlace($v->fasin_code,$year.'-03');


            $year = date('Y',strtotime('-1 year'));
            $v->contractData12 = $this->getFasinOrderPlace($v->fasin_code,$year.'-10');
            $v->contractData34 = $this->getFasinOrderPlace($v->fasin_code,$year.'-11');
            $v->contractData56 = $this->getFasinOrderPlace($v->fasin_code,$year.'-12');

            $v->year = (string)$v->year;


        }

        $posttype = $params['posttype']??1;
        if($posttype==2){

            foreach ($list as $v) {
                # code...
                //销售收入 
                $v->sales_revenue1 = $v->sales_revenu['sales_revenue1'];
                $v->sales_revenue2 = $v->sales_revenu['sales_revenue2'];
                $v->sales_revenue3 = $v->sales_revenu['sales_revenue3'];
                $v->sales_revenue4 = $v->sales_revenu['sales_revenue4'];
                $v->sales_revenue5 = $v->sales_revenu['sales_revenue5'];
                $v->sales_revenue6 = $v->sales_revenu['sales_revenue6'];
                $v->sales_revenue7 = $v->sales_revenu['sales_revenue7'];
                $v->sales_revenue8 = $v->sales_revenu['sales_revenue8'];
                $v->sales_revenue9 = $v->sales_revenu['sales_revenue9'];
                $v->sales_revenue10 = $v->sales_revenu['sales_revenue10'];
                $v->sales_revenue11 = $v->sales_revenu['sales_revenue11'];
                $v->sales_revenue12 = $v->sales_revenu['sales_revenue12'];
                //销售成本 
                $v->cost_of_sales1 = $v->cost_of_sales['cost_of_sales1'];
                $v->cost_of_sales2 = $v->cost_of_sales['cost_of_sales2'];
                $v->cost_of_sales3 = $v->cost_of_sales['cost_of_sales3'];
                $v->cost_of_sales4 = $v->cost_of_sales['cost_of_sales4'];
                $v->cost_of_sales5 = $v->cost_of_sales['cost_of_sales5'];
                $v->cost_of_sales6 = $v->cost_of_sales['cost_of_sales6'];
                $v->cost_of_sales7 = $v->cost_of_sales['cost_of_sales7'];
                $v->cost_of_sales8 = $v->cost_of_sales['cost_of_sales8'];
                $v->cost_of_sales9 = $v->cost_of_sales['cost_of_sales9'];
                $v->cost_of_sales10 = $v->cost_of_sales['cost_of_sales10'];
                $v->cost_of_sales11 = $v->cost_of_sales['cost_of_sales11'];
                $v->cost_of_sales12 = $v->cost_of_sales['cost_of_sales12'];
                //净销售数量 
                $v->net_sales = 0;
                //净销售收入
                $v->net_sales_revenue = 0;
                 //净销售成本
                $v->net_cost_of_sales1 = $v->net_cost_of_sales['net_cost_of_sales1'];
                $v->net_cost_of_sales2 = $v->net_cost_of_sales['net_cost_of_sales2'];
                $v->net_cost_of_sales3 = $v->net_cost_of_sales['net_cost_of_sales3'];
                $v->net_cost_of_sales4 = $v->net_cost_of_sales['net_cost_of_sales4'];
                $v->net_cost_of_sales5 = $v->net_cost_of_sales['net_cost_of_sales5'];
                $v->net_cost_of_sales6 = $v->net_cost_of_sales['net_cost_of_sales6'];
                $v->net_cost_of_sales7 = $v->net_cost_of_sales['net_cost_of_sales7'];
                $v->net_cost_of_sales8 = $v->net_cost_of_sales['net_cost_of_sales8'];
                $v->net_cost_of_sales9 = $v->net_cost_of_sales['net_cost_of_sales9'];
                $v->net_cost_of_sales10 = $v->net_cost_of_sales['net_cost_of_sales10'];
                $v->net_cost_of_sales11 = $v->net_cost_of_sales['net_cost_of_sales11'];
                $v->net_cost_of_sales12 = $v->net_cost_of_sales['net_cost_of_sales12'];
                //手续费
                $v->handling = 0;
                //其他费
                $v->other1 = $v->other['other1'];
                $v->other2 = $v->other['other2'];
                $v->other3 = $v->other['other3'];
                $v->other4 = $v->other['other4'];
                $v->other5 = $v->other['other5'];
                $v->other6 = $v->other['other6'];
                $v->other7 = $v->other['other7'];
                $v->other8 = $v->other['other8'];
                $v->other9 = $v->other['other9'];
                $v->other10 = $v->other['other10'];
                $v->other11 = $v->other['other11'];
                $v->other12 = $v->other['other12'];
                //fba配送费用
                $v->fba = 0;
                //fba仓储费
                $v->fba_inventory = 0;
                //折扣费
                $v->dec = 0;
                //毛利率
                $v->gross_profit_rate = 0;
                //毛利
                $gross_profit = 0;
                 //广告费
                $ad = 0;
                //线下费用 
                $unline = 0;
            }

            $p['title']='fasin预算报表'.time();
            $p['title_list']  = [
                'fasin'=>'fasin',
                'fasin_code'=>'fasin代号',
                'year'=>'年份',
                'season'=>'季节',
                'shop_name'=>'店铺名',
                'is_new'=>'新旧品',
                'role'=>'角色',
                'cost_price'=>'成本单价',
                'return_rate'=>'退货率',
                'month_sales1'=>'1月月销',
                'month_sales2'=>'2月月销',
                'month_sales3'=>'3月月销',
                'month_sales4'=>'4月月销',
                'month_sales5'=>'5月月销',
                'month_sales6'=>'6月月销',
                'month_sales7'=>'7月月销',
                'month_sales8'=>'8月月销',
                'month_sales9'=>'9月月销',
                'month_sales10'=>'10月月销',
                'month_sales11'=>'11月月销',
                'month_sales12'=>'12月月销',
                'month_price1'=>'1月均价',
                'month_price2'=>'2月均价',
                'month_price3'=>'3月均价',
                'month_price4'=>'4月均价',
                'month_price5'=>'5月均价',
                'month_price6'=>'6月均价',
                'month_price7'=>'7月均价',
                'month_price8'=>'8月均价',
                'month_price9'=>'9月均价',
                'month_price10'=>'10月均价',
                'month_price11'=>'11月均价',
                'month_price12'=>'12月均价',
                'ad_spend1'=>'1月acos',
                'ad_spend2'=>'2月acos',
                'ad_spend3'=>'3月acos',
                'ad_spend4'=>'4月acos',
                'ad_spend5'=>'5月acos',
                'ad_spend6'=>'6月acos',
                'ad_spend7'=>'7月acos',
                'ad_spend8'=>'8月acos',
                'ad_spend9'=>'9月acos',
                'ad_spend10'=>'10月acos',
                'ad_spend11'=>'11月acos',
                'ad_spend12'=>'12月acos',
                'sales_revenue1'=>'1月销售收入',
                'sales_revenue2'=>'2月销售收入',
                'sales_revenue3'=>'3月销售收入',
                'sales_revenue4'=>'4月销售收入',
                'sales_revenue5'=>'5月销售收入',
                'sales_revenue6'=>'6月销售收入',
                'sales_revenue7'=>'7月销售收入',
                'sales_revenue8'=>'8月销售收入',
                'sales_revenue9'=>'9月销售收入',
                'sales_revenue10'=>'10月销售收入',
                'sales_revenue11'=>'11月销售收入',
                'sales_revenue12'=>'12月销售收入',
                'cost_of_sales1'=>'1月销售成本',
                'cost_of_sales2'=>'2月销售成本',
                'cost_of_sales3'=>'3月销售成本',
                'cost_of_sales4'=>'4月销售成本',
                'cost_of_sales5'=>'5月销售成本',
                'cost_of_sales6'=>'6月销售成本',
                'cost_of_sales7'=>'7月销售成本',
                'cost_of_sales8'=>'8月销售成本',
                'cost_of_sales9'=>'9月销售成本',
                'cost_of_sales10'=>'10月销售成本',
                'cost_of_sales11'=>'11月销售成本',
                'cost_of_sales12'=>'12月销售成本',
                'net_cost_of_sales1'=>'1月净销售成本',
                'net_cost_of_sales2'=>'2月净销售成本',
                'net_cost_of_sales3'=>'3月净销售成本',
                'net_cost_of_sales4'=>'4月净销售成本',
                'net_cost_of_sales5'=>'5月净销售成本',
                'net_cost_of_sales6'=>'6月净销售成本',
                'net_cost_of_sales7'=>'7月净销售成本',
                'net_cost_of_sales8'=>'8月净销售成本',
                'net_cost_of_sales9'=>'9月净销售成本',
                'net_cost_of_sales10'=>'10月净销售成本',
                'net_cost_of_sales11'=>'11月净销售成本',
                'net_cost_of_sales12'=>'12月净销售成本',
                'other1'=>'1月其他费',
                'other2'=>'2月其他费',
                'other3'=>'3月其他费',
                'other4'=>'4月其他费',
                'other5'=>'5月其他费',
                'other6'=>'6月其他费',
                'other7'=>'7月其他费',
                'other8'=>'8月其他费',
                'other9'=>'9月其他费',
                'other10'=>'10月其他费',
                'other11'=>'11月其他费',
                'other12'=>'12月其他费',
                'fba_inventory_num'=>'fba库存',
                'total_income'=>'合计收入',
                'total_count'=>'合计数',
                'total_avg_price'=>'均价',
                'organizes'=>'部门',
                'country'=>'国家'
            ];

            // $this->excel_expord($p);
                
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = 'fasin预算报表-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }



        return ['data' => $list,'totalnum' => $totalnum];
    }


    //fasin-sku列表
    public function GetFasinSkusM($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }
        $list = db::table('self_sku as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->leftjoin('self_color_size as c','b.color_id','=','c.id')->leftjoin('self_spu_info as spi','b.base_spu_id','=','spi.base_spu_id');
        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }
        if(isset($params['fasin'])){
            $list = $list->where('a.fasin',$params['fasin']);
        }

        if(isset($params['spu'])){
            $spus = explode(',',$params['spu']);

            if(is_array($spus)){
                $spu_res = db::table('self_spu')->whereIn('spu', $spus)->orwhereIn('old_spu', $spus)->get()->toarray();
                $spu_ids = array_column($spu_res,'id');
            }else{
                $spu_res = db::table('self_spu')->where('spu', $spus)->orwhere('old_spu', $spus)->first();
                if($spu_res){
                    $spu_ids[] = $spu_res->id;
                }
            }

            if(count($spu_ids)>0){
                $list = $list->whereIn('a.spu_id',$spu_ids);
            }

        }

        $totalnum = $list->count();
        $list = $list->select('a.*','a.id as sku_id','b.id as custom_sku_id','b.custom_sku','b.size','b.old_custom_sku','b.name','b.tongan_inventory','b.quanzhou_inventory','b.factory_num','b.cloud_num','b.deposit_inventory','c.english_name as color','spi.unit_price')->offset($pagenNum)->limit($limit)->get();

        foreach ($list as $v) {
            # code...
            $v->fasin_code = '';
            $fasin_bind = db::table('amazon_fasin_bind')->where('fasin',$v->fasin)->where('shop_id',$v->shop_id)->first();
            if($fasin_bind){
                $v->fasin_code = $fasin_bind->fasin_code;
            }    
        }
        return ['data' => $list,'totalnum' => $totalnum];
    }


    //款号预算
    public function SaveFasinCusPlanM($params){
        $insert['spu'] = $params['spu'];
        $insert['spu_id'] = $params['spu_id'];
        $insert['color'] = $params['color'];
        $insert['size'] = $params['size'];
        $insert['color_name'] = $params['color_name'];
        $insert['fasin_code'] = $params['fasin_code'];
        $insert['num'] = $params['num'];
        $insert['user_id'] = $params['user_id'];
        $insert['moon'] = $params['moon'];
        $insert['year'] = date('Y',time()); 
        $cus = db::table('self_custom_sku')->where('spu_id',$insert['spu_id'])->where('size',$insert['size'])->where('color',$insert['color'])->first();
        if(!$cus){
            return['type'=>'fail','msg'=>'无此款号'];
        }
        $insert['custom_sku'] = $cus->custom_sku;
        $insert['custom_sku_id'] = $cus->id;
        $insert['create_time'] = date('Y-m-d H:i:s',time());
        db::table('amazon_fasin_cusplan')->insert($insert);
        return ['msg'=>'添加成功','type'=>'success'];
    }


    //款号预算列表
    public function FasinCusPlanListM($params){
        $fasin_code = $params['fasin_code'];
        $year = date('Y',time());
        $list = db::table('amazon_fasin_cusplan')->where('year',$year)->where('fasin_code',$fasin_code)->get();
        foreach ($list as $v) {
            $v->user = $this->GetUsers($v->user_id)['account'];
            # code...
        }
        return ['data'=>$list,'type'=>'success'];
    }


    //删除款号预算
    public function DelCusPlanM($params){
        $id = $params['id'];
        db::table('amazon_fasin_cusplan')->where('id',$id)->delete();
        return ['msg'=>'删除成功','type'=>'success'];
    }
    // //fasin生产下单
    // public function SaveFasinPlaceOrderM($params){
    //     $insert['fasin'] = $params['fasin'];
    //     $insert['shop_id'] = $params['shop_id'];
    //     $insert['fasin_code'] = $params['fasin_code'];
    //     $insert['user_id'] = $params['user_id'];
    //     $insert['create_time'] = date('Y-m-d H:i:s',time());
    //     $insert['status'] = 0;
    //     $order_id = db::table('amazon_fasin_order')->insertGetid($insert);

    //     $data = $params['data'];
    //     foreach ($data as $v) {
    //         # code...
    //         $inserts['order_id'] = $order_id;
    //         $inserts['sku'] = $v['sku']??'';
    //         $inserts['sku_id'] = $v['sku_id']??0;
    //         $inserts['custom_sku'] = $v['custom_sku']??'';
    //         $inserts['custom_sku_id'] = $v['custom_sku_id']??0;
    //         $inserts['spu'] = $v['spu']??'';
    //         $inserts['spu_id'] = $v['spu_id']??0;
    //         $inserts['fasin'] = $params['fasin'];
    //         $inserts['fasin_code'] =  $params['fasin_code'];
    //         $inserts['shop_id'] = $params['shop_id'];
    //         $inserts['num'] = $v['num'];
    //         db::table('amazon_fasin_order_detail')->insert($inserts);
    //     }


    //     // $supply_user = $params['supply_user'];

    //     // $add['one_ids'] = implode(',',$ids);
    //     $add['user_id'] = $params['user_id'];
    //     $add['creattime'] = date('Y-m-d H:i:s',time());
    //     $add['status'] = 0;
    //     $add['content'] = $params['content']??'';
    //     $add['supply_user'] = implode(',',$supply_user);
    //     $add['one_cate_id'] = $taskone->one_cate_id;
    //     $add['two_cate_id'] = $taskone->two_cate_id;
    //     $add['three_cate_id'] = $taskone->three_cate_id;
    //     $spulist = array_values($spulist);
    //     $add['spulist'] = implode(',',$spulist);
    //     $add['sku_count'] = count($skulist);
    //     $add['order_num'] = $order_num;
    //     $add['mode'] = 1;
    //     $add['type'] = $taskone->type;
    //     $task_id = Db::table('amazon_place_order_task')->insertGetId($add);

    //     if($task_id){
    //         foreach ($params['ids'] as $id) {
    //             # code...
    //             DB::table('amazon_team_task_one')->where('id',$id)->update(['status'=>1]);
    //         }


    //         foreach ($detail as $v) {
    //             # code...
    //             $detail_add['spu'] = $this->GetOldSpu($v->spu);
    //             $detail_add['custom_sku'] = $v->custom_sku;
    //             $detail_add['size'] = $v->size;
    //             $detail_add['color_name'] = $v->color_name;
    //             $detail_add['color_name_en'] = $v->color_name_en;
    //             $detail_add['order_num'] = $v->order_num;
    //             $detail_add['order_id'] =  $task_id;
    //             $detail_add['name_en'] = $v->name_en;
    //             $detail_add['spu_id'] = $v->spu_id;
    //             $detail_add['custom_sku_id'] = $v->custom_sku_id;
    //             Db::table('amazon_place_order_detail')->insert($detail_add);
    //         }
    //     }



    //     $return['account'] = $account;
    //     $return['user_id'] = $touser_id;
    //     $return['link'] = '/collective_order_data?list_type=1&order_id='.$task_id;
    //     $return['order_id'] = $task_id;
    //     return ['msg'=>'下单成功','type'=>'success'];
    // }


    //fasin生产下单列表
    public function GetFasinPlaceOrderM($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('amazon_fasin_order_detail as a')->leftjoin('amazon_fasin_order as b','a.order_id','=','b.id');

        if(isset($params['status'])){
            $list = $list->where('b.status',$params['status']);
        }

        if(isset($params['fasin'])){
            $list = $list->where('b.fasin',$params['fasin']);
        }

        if(isset($params['shop_id'])){
            $list = $list->where('b.shop_id',$params['shop_id']);
        }

        if(isset($params['fasin_code'])){
            $list = $list->where('b.fasin_code',$params['fasin_code']);
        }

        if(isset($params['sku'])){
            $skus = db::table('self_sku')->where('sku','like','%'.$params['sku'].'%')->where('old_sku','like','%'.$params['sku'].'%')->get()->toarray();
            $sku_ids = array_column($skus,'id');
            $list = $list->whereIn('a.sku_id',$sku_ids);
        }

        if(isset($params['custom_sku'])){
            $skus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->where('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            $sku_ids = array_column($skus,'id');
            $list = $list->whereIn('a.custom_sku',$sku_ids);
        }


        $totalnum = $list->count();
        $list = $list->offset($pagenNum)->limit($limit)->get();
        foreach ($list as $v) {
            # code...
            $v->user = $this->GetUsers($v->user_id)['account'];
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];
        }
        return ['data' => $list,'totalnum' => $totalnum];
    }

    
    //修改fasin下单状态
    public function UpdateFasinPlaceOrderM($params){
        $order_id = $params['id'];
        $status = $params['status'];
        db::table('amazon_fasin_order')->where('id',$order_id)->update(['status'=>$status]);
        return ['msg'=>'修改状态成功','type'=>'success'];
    }


    public function SaveProfitM($params){
            $p['row'] = ['date_time','settlement_id','type','order_id','sku','description','quantity','marketplace','account_type','fulfillment','order_city','order_state','order_postal','tax_collection_model','product_sales','product_sales_tax','shipping_credits','shipping_credits_tax','gift_wrap_credits','giftwrap_credits_tax','Regulatory_Fee','Tax_On_Regulatory_Fee','promotional_rebates','promotional_rebates_tax','marketplace_withheld_tax','selling_fees','fba_fees','other_transaction_fees','other','total'];
            $p['file'] = $params['file'];
            $p['start'] = 9;
            $data =  $this->CommonExcelImport($p);
            foreach ($data as $v) {
                # code...
                db::table('amazon_profit')->insert($v);
            }
       
            return ['msg'=>'导入成功','type'=>'success'];
    }


    public function GetProfitM($params){

        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('amazon_profit');

        $totalnum = $list->count();
        $list = $list->offset($pagenNum)->limit($limit)->get();

        return ['data' => $list,'totalnum' => $totalnum];
    }

    // public function GetProfitM($params){

    //     $list = db::table('self_custom_sku')->get();
    //     $newdata = [];
    //     foreach ($list as $v) {
    //         # code...
    //         $key = $v->base_spu_id.$v->size;
    //         $newdata[$key]['base_spu_id'] = $v->base_spu_id;
    //         $newdata[$key]['size'] = $v->size;
    //         $color_id = db::table('self_color_size')->where('identifying',$v->size)->first();
    //         if($color_id){
    //             $newdata[$key]['size_id'] = $color_id->id;
    //         }
           
    //     }

    //     foreach ($newdata  as $v) {
    //         # code...
    //         db::table('self_spu_size')->insert($v);
    //     }
 
    //     $totalnum = 0;
    //     return ['data' => $list,'totalnum' => $totalnum];
    // }

    //获取fasin每日详情
    public function GetFasinReportM($params){
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $fasin = $params['fasin'];
        $day = ceil((strtotime($end_time)-strtotime($start_time))/86400)+1;

        $newdata = [];
        for ($i=0; $i < $day; $i++) { 
            # code...
            $today = strtotime($start_time)+($i*86400);
            $today = date('Y-m-d',$today);
            $res = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.fasin',$fasin)->where('b.ds','like','%'.$today.'%')->select('a.*')->first();
            $newdata[$i]['time'] = $today;
            $newdata[$i]['fasin'] =  $fasin;
            $newdata[$i]['sales_num'] = 0;
            $newdata[$i]['sales_price'] = 0;
            $newdata[$i]['ad_price'] = 0;
            $newdata[$i]['ad_sales'] = 0;
            $newdata[$i]['acos'] = 0;
            $newdata[$i]['tacos'] = 0;
            $newdata[$i]['fba_inventory'] = 0;
            $newdata[$i]['cate_rank'] = 0;
            if($res){
                $newdata[$i]['sales_num'] = $res->sales_num;
                $newdata[$i]['sales_price'] = $res->sales_price;
                $newdata[$i]['ad_price'] = $res->ad_price;
                $newdata[$i]['ad_sales'] = $res->ad_sales;
                $newdata[$i]['acos'] = $res->acos;
                $newdata[$i]['tacos'] = $res->tacos;
                $newdata[$i]['fba_inventory'] = $res->fba_inventory;
                $newdata[$i]['cate_rank'] = $res->cate_rank;
            }
        }
        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='fasin日期详情表'.time();
            $p['title_list'] = [
                'time'=>'日期',
                'fasin' => '父Asin',
                'sales_num' => '销量',
                'sales_price'=>'销售额',
                'ad_price'=>'广告费用',
                'ad_sales'=>'广告销售额',
                'cate_rank'=>'大类排名',
                'fba_inventory'=>'fba仓库存',
                'acos'=>'acos',
                'tacos'=>'tacos',
            ];

            $p['data'] =   $newdata;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = 'fasin日期详情表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        return ['type'=>'success','data'=>$newdata]; 
    }

    public function CheckCus($params){
        $custom_sku = $params['custom_sku'];
        $cus_id = Redis::Hget('datacache:cuscheck',$custom_sku);
        if(!$cus_id){
            $cus = db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku',$custom_sku)->first();
            $cus_id = 0;
            if($cus){
                $cus_id = $cus->id;
                Redis::Hset('datacache:cuscheck',$custom_sku,$cus->id);
            }else{
                $product = db::table('product_detail')->where('fnsku',$custom_sku)->first();
                if($product){

                    if($product->custom_sku_id>0){
                        $cus_id = $product->custom_sku_id;
                        $cus = db::table('self_custom_sku')->where('id',$cus_id)->first();
                        if($cus){
                            $custom_sku = $cus->custom_sku;
                            if(!empty($cus->old_custom_sku)){
                                $custom_sku = $cus->old_custom_sku;
                            }
                        }
                    }
                   
                }else{
                    $seller_sku = db::table('self_sku')->where('sku',$custom_sku)->orwhere('old_sku',$custom_sku)->first();
                    if($seller_sku){
                        $custom_sku = $seller_sku->custom_sku;
                        $cus_id = $seller_sku->custom_sku_id;
                    }else{
                        // $saihe = Redis::Hget('datacache:saihe_cus',$custom_sku);
                        $saihe = db::table('saihe_product')->where('client_sku',$custom_sku)->first();
                        if($saihe){
                            $cus_id = 99999999;
                        }else{
                            $cus_id = 0;
                        }
                    }
       
                }
            }
        }

        return ['type'=>'success','custom_sku_id'=>$cus_id,'custom_sku'=>$custom_sku];
    }




    public function GetCusCount($params){

        // $list = db::table('saihe_product')->groupby('client_sku')->select('client_sku','product_name_cn')->get();
        // $c = db::table('self_custom_sku')->select('old_custom_sku','custom_sku','id')->get()->toArray();

        // $cs = array_column($c,'old_custom_sku');

        // foreach ($list as $v) {
            
        //     if(!in_array($v->client_sku,$cs)){
        //         $res['custom_sku'] = $v->client_sku;
        //         $res['custom_sku_id'] = 9999999;
        //         Redis::Hset('check_saihe_cus',$v->client_sku,json_encode($res));
        //     }
        //     # code...
        // }


    //    foreach ($c as $v) {
    //         $res['custom_sku'] = $v->custom_sku;
    //         $res['custom_sku_id'] = $v->id;
    //         Redis::Hset('check_saihe_cus',$v->custom_sku,json_encode($res));
    //         if(!empty($v->old_custom_sku)){
    //             $res['custom_sku'] = $v->old_custom_sku;
    //             $res['custom_sku_id'] = $v->id;
    //             Redis::Hset('check_saihe_cus',$v->old_custom_sku,json_encode($res));
    //         }
    //     # code...
    //    }

    //    $p = db::table('product_detail')->select('fnsku','custom_sku_id')->get();

    //    foreach ($p  as $v) {
    //         $cuss = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();

    //         if($cuss){
    //             $res['custom_sku'] = $cuss->custom_sku;
    //             if(!empty($cuss->old_custom_sku)){
    //                 $res['custom_sku'] = $cuss->old_custom_sku;
    //             }
    //             $res['custom_sku_id'] = $v->custom_sku_id;
    //             Redis::Hset('check_saihe_cus',$v->fnsku,json_encode($res));
    //         }
    //     # code...
    //    }

//        $ds = date('Y-m-d',time());
        if(isset($params['ds'])){
            $ds = date('Y-m-d',strtotime($params['ds']));
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('custom_sku_count')->where('is_del',0)->where('custom_sku_id','>',0);

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $params['end_time'] = $params['end_time']." 23:59:59";
            $list =  $list->whereBetween('create_time', [$params['start_time'], $params['end_time']]);
        }else{
            if (isset($ds)){
                $list = $list->where('create_time','like','%'.$ds.'%');
            }
        }
        if(isset($params['custom_sku'])){
            // DB::connection()->enableQueryLog();
            $cus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            // print_r(DB::getQueryLog());
            $cus_id = array_column($cus,'id');
            // var_dump($cus);
            $list =  $list->where(function($query) use($params,$cus_id){
                $query->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhereIn('custom_sku_id',$cus_id);
            });
        }
        if(isset($params['warehouse_id'])){
            $list =  $list->where('warehouse_id',$params['warehouse_id']);
        }

        if(isset($params['is_self'])){
            if($params['is_self']==1){
                $list =  $list->where('custom_sku_id','<',9999998);
            }else{
                $list =  $list->where('custom_sku_id',9999999);
            }
        }

        if(isset($params['location_code'])){
            $list =  $list->where('location_code','like','%'.$params['location_code'].'%');
        }
        if(isset($params['user_id'])){
            $list =  $list->where('user_id',$params['user_id']);
        }
        if(isset($params['no'])){
            $no = explode(',', trim($params['no']));
            $list =  $list->whereIn('no',$no);
        }


        $total_arr = $list->select('count')->get();
        $total = 0;
        foreach ($total_arr as $v) {
            # code...
            $total+=$v->count;
        }
        
//        $totalnum = $list->groupby('custom_sku')->get()->count();



        $posttype = $params['posttype']??1;

        if($posttype==2){
//            $list = $list->select('id','custom_sku','custom_sku_id','create_time','user_id','warehouse_id','location_code',DB::raw('GROUP_CONCAT(no) as no'),DB::raw('sum(count) as count'))->groupby('custom_sku');
            $totalnum = $list->count();
            $list = $list->select('*');
        }else{
//            $list = $list->select('id','custom_sku','custom_sku_id','create_time','user_id','warehouse_id','location_code',DB::raw('GROUP_CONCAT(no) as no'),DB::raw('sum(count) as count'))->offset($pagenNum)->limit($limit)->groupby('custom_sku');
            $totalnum = $list->count();
            $list = $list->offset($pagenNum)->limit($limit)->select('*');
        }
//        $totalnum = $list->groupby('custom_sku')->get()->count();
//        $list = $list->select('id','custom_sku','custom_sku_id','create_time','user_id','warehouse_id','location_code',DB::raw('GROUP_CONCAT(no) as no'),DB::raw('sum(count) as count'))->offset($pagenNum)->limit($limit)->groupby('custom_sku');

        if(isset($params['order_type'])&&isset($params['order_word'])){

            $list =  $list->orderby($params['order_word'],$params['order_type']);
        }

        $list = $list->get();

        $saihe_cus = [];
        $self_cus = [];

        foreach ($list as $v) {
            if($v->custom_sku_id==9999999){
                $saihe_cus[$v->custom_sku] = $v->custom_sku;
            }elseif($v->custom_sku_id>0){
                $self_cus[$v->custom_sku_id] = $v->custom_sku_id;
            }
        }


        $saihe_cuses = db::table('saihe_product')->whereIn('client_sku',$saihe_cus)->select('client_sku','product_name_cn')->get();
        $self_cuses = db::table('self_custom_sku')->whereIn('id',$self_cus)->select('id','name','base_spu_id')->get()->toarray();

        // $base_spu_ids = array_column($self_cuses,'base_spu_id');

        $base_spu_ress = db::table('self_base_spu')->get();

        $base_spu_res =[];
        foreach ($base_spu_ress as $v) {
            # code...
            $base_spu_res[$v->id]['one_cate_id'] = $v->one_cate_id;
            $base_spu_res[$v->id]['one_cate'] = $this->GetCategory($v->one_cate_id)['name'];
            $base_spu_res[$v->id]['two_cate_id'] = $v->two_cate_id;
            $base_spu_res[$v->id]['two_cate'] = $this->GetCategory($v->two_cate_id)['name'];
            $base_spu_res[$v->id]['three_cate_id'] = $v->three_cate_id;
            $base_spu_res[$v->id]['three_cate'] = $this->GetCategory($v->three_cate_id)['name'];

        }


        $saihe_res = [];
        foreach ($saihe_cuses as $v) {
            # code...
            $saihe_res[$v->client_sku] = $v->product_name_cn;
        }

        $self_cus = [];

        foreach ($self_cuses as $v) {
            # code...
            $self_cus[$v->id]['name'] = $v->name;
            $self_cus[$v->id]['cate'] = '';
            if($v->base_spu_id>0){
                $self_cus[$v->id]['cate'] = $base_spu_res[$v->base_spu_id]['one_cate'].$base_spu_res[$v->base_spu_id]['three_cate'];
            }

        }

        foreach ($list as $v) {
            # code...

            $v->price = $this->GetCustomSkuPrice($v->custom_sku);
            $v->user = $this->GetUsers($v->user_id)['account']??'';
            $v->is_self = '是';
            $v->name = '';
            $v->cate = '';
            if($v->custom_sku_id==9999999){
                $v->is_self = '否';
                $v->name = $saihe_res[$v->custom_sku];
            }elseif($v->custom_sku_id>0){
                if(isset($self_cus[$v->custom_sku_id]['name'])){
                    $v->name =  $self_cus[$v->custom_sku_id]['name'];
                }
                if(isset($self_cus[$v->custom_sku_id]['cate'])){
                    $v->cate = $self_cus[$v->custom_sku_id]['cate'];
                }
            }

            if($v->warehouse_id==1){
                $v->warehouse = '同安';
            }else{
                $v->warehouse = '泉州';
            }

            $no = explode(',',$v->no);
            $gp['user_id'] =  $v->user_id;
            $ds = date('Y-m-d',strtotime($v->create_time));
            $gp['ds'] =  $ds;
//            $no_new = [];
//            if(is_array($no)){
//                foreach ($no as $nov) {
//                    # code...
//                    $gp['no'] =  $nov;
//                    $no_new[] = $this->GetNo($gp);
//                }
//
//            }else{
//                $gp['no'] =  $v->no;
//                $no_new[] = $this->GetNo($gp);
//            }
//
//            $v->no = implode(',',$no_new);
            $gp['no'] =  $v->no;
            $v->no = $this->GetNo($gp)."\t";
            $customSkuMdl = db::table('self_custom_sku')->where('id', $v->custom_sku_id)->first();
            $v->new_custom_sku = $customSkuMdl->custom_sku  ?? $v->custom_sku;
            $v->old_custom_sku = $customSkuMdl->old_custom_sku ?? '';
        }

        if($posttype==2){
            $p['title']='库存盘点清单'.time();


            $listtlt = [
                'new_custom_sku'=>'新库存SKU',
                'old_custom_sku' => '旧库存SKU',
                'name'=>'产品名',
                'cate'=>'分类',
                'is_self'=>'是否在系统',
                'warehouse'=>'仓库',
                'location_code'=>'库位编码',
                'no'=>'批次',
                'count'=>'数量',
                'price'=>'采购价格',
                'user'=>'操作人',
                'create_time'=>'创建时间'
            ];


            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = $params['find_user_id'];
            // $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '库存盘点清单-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return ['data' => $list,'totalnum' => $totalnum,'total'=>$total];
    }


    public function Instore($params){
        $warehouse_id  =$params['warehouse_id']??1;
        $list = Db::table('custom_sku_count')->where('is_del',0)->where('custom_sku_id','>',0)->where('custom_sku_id','<',9999998)->where('is_instore',0)->where('id','>',16897)->where('new_custom_sku','!=','')->where('warehouse_id',$warehouse_id)->select(DB::raw('GROUP_CONCAT(custom_sku_id) as ids'),'location_code',DB::raw('GROUP_CONCAT(custom_sku_id) as custom_sku'),DB::raw('GROUP_CONCAT(count) as count'))->groupby('location_code');
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 5;
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = $list->offset($pagenNum)->limit($limit)->get();

        $newdata = [];
        $ni = 0;

        $ids = [];
        foreach ($list as $v) {
            // $cus = db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $cuss = explode(',', trim($v->custom_sku));
            $counts = explode(',', trim($v->count));
            $ids[] = $v->ids;
            // $ids = explode(',', trim($v->id));
            $cdata = [];
            foreach ($cuss as $key => $value) {
                # code...
                $cdata[$key]['custom_sku'] = db::table('self_custom_sku')->where('id',$cuss[$key])->first()->custom_sku;
                $cdata[$key]['count'] = $counts[$key];
            }
            $newdata[$ni]['location_code'] = $v->location_code;
            $newdata[$ni]['cus_data'] = $cdata;
            $newdata[$ni]['id'] = explode(',', trim($v->ids));
            $ni++;
            # code...
        }

        // return ['data'=>$newdata,'list'=>$list];
        $order_no = [];
        db::beginTransaction();    //开启事务
       
        $returndata = [];
        foreach ($newdata as $v) {

            $v['location_code'] = 'A01-001';
            $location = db::table('cloudhouse_warehouse_location')->where('warehouse_id',$warehouse_id)->where('location_code',$v['location_code'])->first();
            if(!$location){
                    return ['msg'=>'无此库位'.$v['location_code']];
                    db::rollback();// 回调
            }
            $location_id = $location->id;
            $skuData = [];
            $i = 0;
            $data = $v['cus_data'];
            foreach ($data  as $dv) {
                $skuData[$i]['custom_sku'] = $dv['custom_sku'];
                $skuData[$i]['num'] = $dv['count'];
                $skuData[$i]['location_id'] =  $location_id;
                $i++;
                # code...
            }
            $instore['skuData'] = $skuData;
            $instore['type_detail'] = 3;
            $instore['type'] = 5;
            $instore['in_house'] = $warehouse_id;
            $instore['remark'] = '盘点入库';
            $u = db::table('users')->where('account','admin')->first();
            $instore['token'] =  $u->token;
            $instore['platform_id'] = 4;
            $invetoryModel = new InventoryModel();
            try {
                //code...
                $out_msg = $invetoryModel->goods_transfers($instore);
            } catch (\Throwable $th) {
                //throw $th;
                db::rollback();// 回调
                return ['msg'=>$th->getMessage().'file:'.$th->getFile().'line:'.$th->getline(),'data'=>$instore];
            }

            if($out_msg['code']!=200){
                db::rollback();// 回调
                $rt["msg"]= '入库失败'.$out_msg['msg'].json_encode($v);
                return $rt;
            }

            $order_no[] = $out_msg['id'];

            Db::table('custom_sku_count')->whereIn('id',$v['id'])->update(['is_instore'=>1]);
            // $returndata[] =  $order_no;
            # code...
        }

        db::commit();
        return ['data'=>$newdata,'return'=>$order_no,'list'=>$list];
    }


    public function GetCusCountSelf($params){
//        $ds = date('Y-m-d',time());
        if(isset($params['ds'])){
            $ds = date('Y-m-d',strtotime($params['ds']));
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('custom_sku_count as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->leftjoin('self_base_spu as c','b.base_spu_id','=','c.id')->where('a.is_del',0)->where('a.custom_sku_id','>',0)->where('a.custom_sku_id','<',9999998);

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $params['end_time'] = $params['end_time']." 23:59:59";
            $list =  $list->whereBetween('a.create_time', [$params['start_time'], $params['end_time']]);
        }else{
            if (isset($ds)){
                $list = $list->where('a.create_time','like','%'.$ds.'%');
            }
        }
        if(isset($params['custom_sku'])){
            // DB::connection()->enableQueryLog();
            $cus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            // print_r(DB::getQueryLog());
            $cus_id = array_column($cus,'id');
            // var_dump($cus);
            $list =  $list->where(function($query) use($params,$cus_id){
                $query->where('a.custom_sku','like','%'.$params['custom_sku'].'%')->orwhereIn('a.custom_sku_id',$cus_id);
            });
        }
        if(isset($params['warehouse_id'])){
            $list =  $list->where('a.warehouse_id',$params['warehouse_id']);
        }
        if(isset($params['is_self'])){

            if($params['is_self']==1){
                $list =  $list->where('a.custom_sku_id','<',9999998);
            }else{
                $list =  $list->where('a.custom_sku_id',9999999);
            }

        }
        if(isset($params['location_code'])){
            $list =  $list->where('a.location_code','like','%'.$params['location_code'].'%');
        }
        if(isset($params['user_id'])){
            $list =  $list->where('a.user_id',$params['user_id']);
        }
        if(isset($params['no'])){
            $no = explode(',', trim($params['no']));
            $list =  $list->whereIn('a.no',$no);
        }

        if(isset($params['one_cate_id'])){
            $list =  $list->whereIn('c.one_cate_id',$params['one_cate_id']);
        }

        if(isset($params['two_cate_id'])){
            $list =  $list->whereIn('c.two_cate_id',$params['two_cate_id']);
        }

        if(isset($params['three_cate_id'])){
            $list =  $list->whereIn('c.three_cate_id',$params['three_cate_id']);
        }

        if(isset($params['name'])){
            $list =  $list->where('b.name','like','%'.$params['name'].'%');
        }


        $total_arr = $list->select('a.count')->get();
        $total = 0;
        foreach ($total_arr as $v) {
            # code...
            $total+=$v->count;
        }

//        $totalnum = $list->groupby('a.custom_sku')->get()->count();



        $posttype = $params['posttype']??1;

        if($posttype==2){
//            $list = $list->select('a.id','b.custom_sku','b.old_custom_sku','b.name','c.one_cate_id','c.two_cate_id','c.three_cate_id','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code',DB::raw('GROUP_CONCAT(a.no) as no'),DB::raw('sum(a.count) as count'))->groupby('a.custom_sku');
            $totalnum = $list->count();
            $list = $list->select('a.id','b.custom_sku','b.old_custom_sku','b.name','c.one_cate_id','c.two_cate_id','c.three_cate_id','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code','a.no','a.count');
        }else{
//            $list = $list->select('a.id','b.custom_sku','b.old_custom_sku','b.name','c.one_cate_id','c.two_cate_id','c.three_cate_id','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code',DB::raw('GROUP_CONCAT(a.no) as no'),DB::raw('sum(a.count) as count'))->offset($pagenNum)->limit($limit)->groupby('a.custom_sku');
            $totalnum = $list->count();
            $list = $list->offset($pagenNum)->limit($limit)->select('a.id','b.custom_sku','b.old_custom_sku','b.name','c.one_cate_id','c.two_cate_id','c.three_cate_id','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code','a.no','a.count');
        }
        if(isset($params['order_type'])&&isset($params['order_word'])){

            $list =  $list->orderby('a.'.$params['order_word'],$params['order_type']);
        }

        $list = $list->get();


        foreach ($list as $v) {
            # code...

            $v->price = $this->GetCustomSkuPrice($v->custom_sku);
            $v->user = $this->GetUsers($v->user_id)['account']??'';
            $v->is_self = '是';
            $v->one_cate = $this->GetCategory($v->one_cate_id)['name'];
            $v->two_cate = $this->GetCategory($v->two_cate_id)['name'];
            $v->three_cate = $this->GetCategory($v->three_cate_id)['name'];


            if($v->warehouse_id==1){
                $v->warehouse = '同安';
            }else{
                $v->warehouse = '泉州';
            }

            $no = explode(',',$v->no);
            $gp['user_id'] =  $v->user_id;
            $ds = date('Y-m-d',strtotime($v->create_time));
            $gp['ds'] =  $ds;
            //            $no_new = [];
//            if(is_array($no)){
//                foreach ($no as $nov) {
//                    # code...
//                    $gp['no'] =  $nov;
//                    $no_new[] = $this->GetNo($gp);
//                }
//
//            }else{
//                $gp['no'] =  $v->no;
//                $no_new[] = $this->GetNo($gp);
//            }
//
//            $v->no = implode(',',$no_new);
            $gp['no'] =  $v->no;
            $v->no = $this->GetNo($gp)."\t";
            $customSkuMdl = db::table('self_custom_sku')->where('id', $v->custom_sku_id)->first();
            $v->new_custom_sku = $customSkuMdl->custom_sku;
            $v->old_custom_sku = $customSkuMdl->old_custom_sku ?? '';
        }

        if($posttype==2){
            $p['title']='库存盘点清单-系统'.time();


            $listtlt = [
                'new_custom_sku'=>'新库存SKU',
                'old_custom_sku' => '旧库存SKU',
                'name'=>'产品名',
                'one_cate'=>'一类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'is_self'=>'是否在系统',
                'warehouse'=>'仓库',
                'location_code'=>'库位编码',
                'no'=>'批次',
                'count'=>'数量',
                'price'=>'采购价格',
                'user'=>'操作人',
                'create_time'=>'创建时间'
            ];


            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = $params['find_user_id'];
            // $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '库存盘点清单-系统-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return ['data' => $list,'totalnum' => $totalnum,'total'=>$total];
    }




    public function GetCusCountSaihe($params){


//        $ds = date('Y-m-d',time());
        if(isset($params['ds'])){
            $ds = date('Y-m-d',strtotime($params['ds']));
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 10;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('custom_sku_count as a')->leftjoin('saihe_product as b','a.custom_sku','=','b.client_sku')->where('a.is_del',0)->where('a.custom_sku_id',9999999);

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $params['end_time'] = $params['end_time']." 23:59:59";
            $list =  $list->whereBetween('a.create_time', [$params['start_time'], $params['end_time']]);
        }else{
            if (isset($ds)){
                $list = $list->where('a.create_time','like','%'.$ds.'%');
            }

        }
        if(isset($params['custom_sku'])){
            // DB::connection()->enableQueryLog();
            // $cus = db::table('self_custom_sku')->where('custom_sku','like','%'.$params['custom_sku'].'%')->orwhere('old_custom_sku','like','%'.$params['custom_sku'].'%')->get()->toarray();
            // // print_r(DB::getQueryLog());
            // $cus_id = array_column($cus,'id');
            // var_dump($cus);
            $list =  $list->where('a.custom_sku','like','%'.$params['custom_sku'].'%');
        }
        if(isset($params['warehouse_id'])){
            $list =  $list->where('a.warehouse_id',$params['warehouse_id']);
        }
        // if(isset($params['is_self'])){

        //     if($params['is_self']==1){
        //         $list =  $list->where('a.custom_sku_id','<',9999998);
        //     }else{
        //         $list =  $list->where('a.custom_sku_id',9999999);
        //     }

        // }
        if(isset($params['location_code'])){
            $list =  $list->where('a.location_code','like','%'.$params['location_code'].'%');
        }
        if(isset($params['user_id'])){
            $list =  $list->where('a.user_id',$params['user_id']);
        }
        if(isset($params['no'])){
            $no = explode(',', trim($params['no']));
            $list =  $list->whereIn('a.no',$no);
        }

        if(isset($params['name'])){
            $list =  $list->where('b.product_name_cn','like','%'.$params['name'].'%');
        }

        // if(isset($params['two_cate_id'])){
        //     $list =  $list->whereIn('c.two_cate_id',$params['two_cate_id']);
        // }

        // if(isset($params['three_cate_id'])){
        //     $list =  $list->whereIn('c.three_cate_id',$params['three_cate_id']);
        // }


        $total_arr = $list->select('a.count')->get();
        $total = 0;
        foreach ($total_arr as $v) {
            # code...
            $total+=$v->count;
        }

        $totalnum = $list->groupby('a.custom_sku')->get()->count();



        $posttype = $params['posttype']??1;

        if($posttype==2){
//            $list = $list->select('a.id','b.product_name_cn as name','a.custom_sku','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code',DB::raw('GROUP_CONCAT(a.no) as no'),DB::raw('sum(a.count) as count'))->groupby('a.custom_sku');
            $totalnum = $list->count();
            $list = $list->select('a.id','b.product_name_cn as name','a.custom_sku','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code', 'a.no', 'a.count');
        }else{
//            $list = $list->select('a.id','b.product_name_cn as name','a.custom_sku','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code',DB::raw('GROUP_CONCAT(a.no) as no'),DB::raw('sum(a.count) as count'))->offset($pagenNum)->limit($limit)->groupby('a.custom_sku');
            $totalnum = $list->count();
            $list = $list->offset($pagenNum)->limit($limit)->select('a.id','b.product_name_cn as name','a.custom_sku','a.custom_sku_id','a.create_time','a.user_id','a.warehouse_id','a.location_code', 'a.no', 'a.count');
        }
        if(isset($params['order_type'])&&isset($params['order_word'])){

            $list =  $list->orderby('a.'.$params['order_word'],$params['order_type']);
        }

        $list = $list->get();


        foreach ($list as $v) {
            # code...

            $v->price = $this->GetCustomSkuPrice($v->custom_sku);
            $v->user = $this->GetUsers($v->user_id)['account']??'';
            $v->is_self = '是';
            $v->one_cate = '';
            $v->two_cate = '';
            $v->three_cate = '';


            if($v->warehouse_id==1){
                $v->warehouse = '同安';
            }else{
                $v->warehouse = '泉州';
            }

            $no = explode(',',$v->no);
            $gp['user_id'] =  $v->user_id;
            $ds = date('Y-m-d',strtotime($v->create_time));
            $gp['ds'] =  $ds;
            //            $no_new = [];
//            if(is_array($no)){
//                foreach ($no as $nov) {
//                    # code...
//                    $gp['no'] =  $nov;
//                    $no_new[] = $this->GetNo($gp);
//                }
//
//            }else{
//                $gp['no'] =  $v->no;
//                $no_new[] = $this->GetNo($gp);
//            }
//
//            $v->no = implode(',',$no_new);
            $gp['no'] =  $v->no;
            $v->no = $this->GetNo($gp)."\t";
            $customSkuMdl = db::table('self_custom_sku')->where('id', $v->custom_sku_id)->first();
            $v->new_custom_sku = $customSkuMdl->custom_sku ?? $v->custom_sku;
            $v->old_custom_sku = $customSkuMdl->old_custom_sku ?? '';
        }

        if($posttype==2){
            $p['title']='库存盘点清单-赛盒'.time();


            $listtlt = [
                'new_custom_sku'=>'新库存SKU',
                'old_custom_sku' => '旧库存SKU',
                'name'=>'产品名',
                'one_cate'=>'一类',
                'two_cate'=>'二类',
                'three_cate'=>'三类',
                'is_self'=>'是否在系统',
                'warehouse'=>'仓库',
                'location_code'=>'库位编码',
                'no'=>'批次',
                'count'=>'数量',
                'price'=>'采购价格',
                'user'=>'操作人',
                'create_time'=>'创建时间'
            ];


            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] = $params['find_user_id'];
            // $p['user_id'] = Db::table('users')->where('token',$params['token'])->first()->Id;
            $p['type'] = '库存盘点清单-赛盒-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }
        return ['data' => $list,'totalnum' => $totalnum,'total'=>$total];
    }







    public function DelCustomSkuCount($params){
        $id = $params['id'];
        Db::table('custom_sku_count')->whereIn('id',$id)->update(['is_del'=>1]);

        return['type'=>'success','msg'=>'删除成功'];
    }

    public function GetNo($params){
        $user_name = $this->GetUsers($params['user_id'])['account'] ?? '';
        $user_code = mb_substr($user_name,2,1);
        $d = '0';
        if (!isset($params['ds']) || empty($params['ds'])){
            return '0'.$user_code.$params['no'];
        }
        $ds = $params['ds'];
        if($ds=='2023-06-12'){$d=1;};if($ds=='2023-06-13'){$d=2;};if($ds=='2023-06-14'){$d=3;};if($ds=='2023-06-15'){$d=4;};if($ds=='2023-06-16'){$d=5;};

        $no = $params['no'];
        $no = str_pad($no, 2, 0, STR_PAD_LEFT);
        $code = $d.$user_code.$no;

        return $code;

    }


    public function CustomSkuCountByCodea($params){

        $count = db::table('custom_sku_count')->where('warehouse_id',$params['warehouse_id'])->groupby('location_code')->select('location_code')->get();

        $fids = [];


        // var_dump($count);
        foreach ($count as $v) {
            $key = db::table('cloudhouse_warehouse_location')->where('location_code',$v->location_code)->first();
            $key2 = db::table('cloudhouse_warehouse_location')->where('id',$key->fid)->first();
            // $key3 = db::table('cloudhouse_warehouse_location')->where('id',$key2->fid)->first();
            $fids[$key2->fid] = $key2->fid;
        }

        // var_dump($fids);
        $fids = array_values($fids);
        $fids[] =15;

        // var_dump($fids);
        $codes = db::table('cloudhouse_warehouse_location')->where('warehouse_id',$params['warehouse_id'])->whereIn('id',$fids)->orderby('sort','ASC')->get();

        foreach ($codes as $v) {
            $v->count = 0;
            $v->box = 0;
            # code...
            $datas = $this->GetTotalByLocation($v->id);

            $v->count = array_sum($datas['count']);
            $v->box =array_sum($datas['box']);
        }
        return ['type'=>'success','data'=>$codes];
    }

    public function GetTotalByLocation($id){
        $key = db::table('cloudhouse_warehouse_location')->where('fid',$id)->get()->toarray();
        $warehouse_id = $key[0]->warehouse_id;
        $ids = array_column($key,'id');
        $key2 = db::table('cloudhouse_warehouse_location')->whereIn('fid',$ids)->get()->toarray();
        $location_codes = array_column($key2,'location_code');
        $res = db::table('custom_sku_count')->whereIn('location_code',$location_codes)->where('warehouse_id',$warehouse_id)->get();
        $count = [];
        $box = [];
        foreach ($res as $v) {
            # code...
            if(isset($count[$v->location_code])){
                $count[$v->location_code] += $v->count;
            }else{
                $count[$v->location_code] = $v->count;
            }

            $key = $v->user_id.$v->no.$v->location_code.$v->create_time;
            if(isset($box[$key])){
                $box[$key] += 1;
            }else{
                $box[$key] = 1;
            }

        }

        return ['count'=>$count,'box'=>$box];
    }

    // public function CustomSkuCountByCodeB($params){
    //     $id = $params['id'];
    //     $codes = db::table('cloudhouse_warehouse_location')->where('fid',$id)->get()->toarray();
    //     $warehouse_id = $codes['0']->warehouse_id;
    //     $codes =  array_column($codes,'id');
    //     $codesb =  db::table('cloudhouse_warehouse_location')->whereIn('fid',$codes)->get()->toarray();
    //     $codesb =  array_column($codesb,'location_code');
    //     // if(isset($params['warehouse_id'])){
    //     //     $codes =  $codes->where('warehouse_id',$params['warehouse_id']);
    //     // }
    //     $datas = db::table('custom_sku_count')->whereIn('location_code',$codesb)->where('warehouse_id',$warehouse_id)->groupby('location_code')->select('location_code')->get()->toarray();
    //     $sort = array_column($datas,'location_code');
    //     // $sort =  sort($sort);
    //     array_multisort($sort,SORT_ASC,$datas);

    //     $total = db::table('custom_sku_count')->whereIn('location_code',$sort)->get();

    //     $total_num= 0;
    //     $total_box= 0;
    //     foreach ($total as $v) {
    //         # code...
    //         if(isset($total_num[$v->location_code]))

    //     }

    //     return ['type'=>'success','data'=>$datas];
    // }

    public function UpdateCustomSkuCount($params){

        $account = $params['a'];
        // $no = $params['no'];
        $type = $params['t']??0;
        // $code = $params['code'];
        // $count = $params['count'];
        $update = [];
        if(isset($params['count'])){
            $update['count'] = $params['count'];
        }

        if(isset($params['code'])){
            $update['location_code'] = $params['code'];
        }

        $users = db::table('users')->where('account',$account)->first();

        $res = db::table('custom_sku_count')->where('user_id',$users->Id);

        if(isset($params['no'])){
            $res =$res->where('no',$params['no']);
        }
        if(isset($params['ds'])){
            $res =$res->where('create_time','like','%'.$params['ds'].'%');
        }


        if($type=='1'){
            $res =$res->update($update);
        }else{
            $res = $res->get();
        }

        // $codes = db::table('custom_sku_count')->where('warehouse_id',$params['warehouse_id'])->where('location_code',$params['location_code'])->where('is_del',0)->get();

        // $newdata = [];
        // foreach ($codes as $v) {
        //     # code...
        //     $key = $v->user_id.$v->no;
        //     if(isset($newdata[$key]['count'])){
        //         $newdata[$key]['count'] +=$v->count;
        //     }else{
        //         $newdata[$key]['count'] =$v->count;
        //     }
        //     $newdata[$key]['user_id'] = $v->user_id;
        //     $newdata[$key]['create_time'] = $v->create_time;
        //     $newdata[$key]['no'] = $v->no;
        // }

        // $newdata = array_values($newdata);

        // foreach ($newdata as &$v) {
        //     # code...
        //     $v['user'] = $this->GetUsers($v['user_id'])['account'];
        //     $gp['user_id'] =  $v['user_id'];
        //     $gp['ds'] =  date('Y-m-d',strtotime($v['create_time']));
        //     $gp['no'] =  $v['no'];
        //     $no_new = $this->GetNo($gp);
        //     $v['no_a'] = $v['no'];
        //     $v['no'] = $no_new;
        // }
        return ['type'=>'success','data'=>$res,'datab'=>$update];
    }


    public function CustomSkuCountByUserc($params){
        $codes = db::table('custom_sku_count');

        if(isset($params['id'])){
            $id = $params['id'];
            $code_s = db::table('cloudhouse_warehouse_location')->where('fid',$id)->get()->toarray();
            $code_s =  array_column($code_s,'id');
            $codesb =  db::table('cloudhouse_warehouse_location')->whereIn('fid',$code_s)->get()->toarray();
            $codesb =  array_column($codesb,'location_code');
            $codes =  $codes->whereIn('location_code',$codesb);
            // $datas = db::table('custom_sku_count')->whereIn('location_code',$codesb)->where('warehouse_id',$warehouse_id)->groupby('location_code')->select('location_code')->get()->toarray();
            // $sort = array_column($datas,'location_code');
        }
        if(isset($params['location_code'])){
            $codes =  $codes->where('location_code',$params['location_code']);
        }
        if(isset($params['warehouse_id'])){
            $codes =  $codes->where('warehouse_id',$params['warehouse_id']);
        }

        // $ds = date('Y-m-d',time());
        // if(isset($params['ds'])){
        //     $ds = date('Y-m-d',strtotime($params['ds']));
        // }


        $codes =  $codes->groupby('location_code')->select('location_code')->get()->toarray();
        $code_ids = array_column($codes,'location_code');

        $total_arr =  db::table('custom_sku_count')->where('is_del',0)->select('location_code','count','no');

        if(isset($params['warehouse_id'])){
            $total_arr =  $total_arr->where('warehouse_id',$params['warehouse_id']);
        }
        $total_arr =$total_arr->get();
        $total = [];
        $totalb= [];

        $id = 1;
        foreach ($total_arr as $v) {
            # code...
            // $total+=$v->count;
            if(isset($total[$v->location_code])){
                $total[$v->location_code]+= $v->count;
            }else{
                $total[$v->location_code] = $v->count;
            }

            $key = $v->location_code.'and'.$v->no;

            if(isset($totalb[$key])){
                $totalb[$key]+= $v->count;
            }else{
                $totalb[$key] = $v->count;
            }

        }

        $datas = [];
        foreach ($code_ids as $v) {
            $data = [];
            $no = db::table('custom_sku_count');
            if(isset($params['warehouse_id'])){
                $no =  $no->where('warehouse_id',$params['warehouse_id']);
            }
            $no =  $no->where('location_code',$v)->where('is_del',0)->select('no','create_time','location_code','user_id')->get();
            $data['nos'] = [];
            $data['id'] =  $id;
            $id++;
            foreach ($no as $nv) {
                # code...
                $nos = [];
                $key =  $v.'and'.$nv->no;

                $gp['user_id'] =  $nv->user_id;
                $ds = date('Y-m-d',strtotime($nv->create_time));
                $gp['ds'] =  $ds;
                $gp['no'] =  $nv->no;
                $no_new = $this->GetNo($gp);
                $nos['no_a'] = $nv->no;
                $nos['no'] = $no_new;
                if(isset($totalb[$key])){
                    $nos['count'] = $totalb[$key];
                }else{
                    $nos['count'] = 0;
                }

                $nos['id'] =$id;
                $id++;
                $nos['create_time'] = $nv->create_time;
                $data['nos'][$nv->no] = $nos;

            }

            $data['nos'] = array_values($data['nos']);
            $data['location_code'] = $v;
            $data['box'] = count($data['nos']);

            if(isset($total[$v])){
                $data['count'] = $total[$v];
            }else{
                $data['count'] = 0;
            }

            $datas[] = $data;
            # code...
        }

        $sort = array_column($datas,'location_code');
        // $sort =  sort($sort);
        array_multisort($sort,SORT_ASC,$datas);
        return ['type'=>'success','data'=>$datas];
    }

    public function CustomSkuCountByUserb($params){
        $codes = db::table('custom_sku_count');

        if(isset($params['id'])){
            $id = $params['id'];
            $code_s = db::table('cloudhouse_warehouse_location')->where('fid',$id)->get()->toarray();
            $code_s =  array_column($code_s,'id');
            $codesb =  db::table('cloudhouse_warehouse_location')->whereIn('fid',$code_s)->get()->toarray();
            $codesb =  array_column($codesb,'location_code');
            $codes =  $codes->whereIn('location_code',$params['location_code']);
            // $datas = db::table('custom_sku_count')->whereIn('location_code',$codesb)->where('warehouse_id',$warehouse_id)->groupby('location_code')->select('location_code')->get()->toarray();
            // $sort = array_column($datas,'location_code');
        }
        if(isset($params['location_code'])){
            $codes =  $codes->where('location_code',$params['location_code']);
        }
        if(isset($params['warehouse_id'])){
            $codes =  $codes->where('warehouse_id',$params['warehouse_id']);
        }

        $ds = date('Y-m-d',time());
        if(isset($params['ds'])){
            $ds = date('Y-m-d',strtotime($params['ds']));
        }


        $codes =  $codes->where('create_time','like','%'.$ds.'%')->groupby('location_code')->select('location_code')->get()->toarray();
        $code_ids = array_column($codes,'location_code');

        $total_arr =  db::table('custom_sku_count')->where('is_del',0)->select('location_code','count','no');

        if(isset($params['warehouse_id'])){
            $total_arr =  $total_arr->where('warehouse_id',$params['warehouse_id']);
        }
        $total_arr =$total_arr->where('create_time','like','%'.$ds.'%');
        $total_arr =$total_arr->get();
        $total = [];
        $totalb= [];

        $id = 1;
        foreach ($total_arr as $v) {
            # code...
            // $total+=$v->count;
            if(isset($total[$v->location_code])){
                $total[$v->location_code]+= $v->count;
            }else{
                $total[$v->location_code] = $v->count;
            }

            $key = $v->location_code.'and'.$v->no;

            if(isset($totalb[$key])){
                $totalb[$key]+= $v->count;
            }else{
                $totalb[$key] = $v->count;
            }

        }

        $datas = [];
        foreach ($code_ids as $v) {
            $data = [];
            $no = db::table('custom_sku_count')->where('create_time','like','%'.$ds.'%');
            if(isset($params['warehouse_id'])){
                $no =  $no->where('warehouse_id',$params['warehouse_id']);
            }
            $no =  $no->where('location_code',$v)->where('is_del',0)->select('no','create_time','location_code','user_id')->get();
            $data['nos'] = [];
            $data['id'] =  $id;
            $id++;
            foreach ($no as $nv) {
                # code...
                $nos = [];
                $key =  $v.'and'.$nv->no;

                $gp['user_id'] =  $nv->user_id;
                $gp['ds'] =  $ds;
                $gp['no'] =  $nv->no;
                $no_new = $this->GetNo($gp);
                $nos['no_a'] = $nv->no;
                $nos['no'] = $no_new;
                if(isset($totalb[$key])){
                    $nos['count'] = $totalb[$key];
                }else{
                    $nos['count'] = 0;
                }

                $nos['id'] =$id;
                $id++;
                $nos['create_time'] = $nv->create_time;
                $data['nos'][$nv->no] = $nos;

            }

            $data['nos'] = array_values($data['nos']);
            $data['location_code'] = $v;
            $data['box'] = count($data['nos']);

            if(isset($total[$v])){
                $data['count'] = $total[$v];
            }else{
                $data['count'] = 0;
            }

            $datas[] = $data;
            # code...
        }

        $sort = array_column($datas,'location_code');
        // $sort =  sort($sort);
        array_multisort($sort,SORT_ASC,$datas);
        return ['type'=>'success','data'=>$datas];
    }


    public function CustomSkuCountByUser($params){
        $users = db::table('custom_sku_count');
        if(isset($params['user_id'])){
            $users =  $users->where('user_id',$params['user_id']);
        }
        if(isset($params['warehouse_id'])){
            $users =  $users->where('warehouse_id',$params['warehouse_id']);
        }



        $ds = date('Y-m-d',time());
        if(isset($params['ds'])){
            $ds = date('Y-m-d',strtotime($params['ds']));
        }


        $users =  $users->where('create_time','like','%'.$ds.'%')->groupby('user_id')->select('user_id')->get()->toarray();
        $user_ids = array_column($users,'user_id');

        $total_arr =  db::table('custom_sku_count')->where('is_del',0)->select('user_id','count','no');

        $total_arr =$total_arr->where('create_time','like','%'.$ds.'%');
        $total_arr =$total_arr->get();
        $total = [];
        $totalb= [];

        $id = 1;
        foreach ($total_arr as $v) {
            # code...
            // $total+=$v->count;
            if(isset($total[$v->user_id])){
                $total[$v->user_id]+= $v->count;
            }else{
                $total[$v->user_id] = $v->count;
            }

            $key = $v->user_id.'and'.$v->no;

            if(isset($totalb[$key])){
                $totalb[$key]+= $v->count;
            }else{
                $totalb[$key] = $v->count;
            }

        }

        $datas = [];
        foreach ($user_ids as $v) {
            $data = [];
            $no = db::table('custom_sku_count')->where('create_time','like','%'.$ds.'%')->where('user_id',$v)->where('is_del',0)->select('no','create_time','location_code')->get();
            $data['nos'] = [];
            $data['id'] =  $id;
            $id++;
            foreach ($no as $nv) {
                # code...
                $nos = [];
                $key =  $v.'and'.$nv->no;

                $gp['user_id'] =  $v;
                $gp['ds'] =  $ds;
                $gp['no'] =  $nv->no;
                $no_new = $this->GetNo($gp);
                // $nos['no_new'] = $no_new;
                $nos['no_a'] = $nv->no;
                $nos['no'] =  $no_new;
                if(isset($totalb[$key])){
                    $nos['count'] = $totalb[$key];
                }else{
                    $nos['count'] = 0;
                }
               
                $nos['id'] =$id;
                $id++;
                $nos['create_time'] = $nv->create_time;
                $nos['location_code'] = $nv->location_code;
                $data['nos'][$nv->no] = $nos;

            }
           
            $data['nos'] = array_values($data['nos']);
            $data['user'] = $this->GetUsers($v)['account'];
            $data['user_id'] = $v;
            $data['box'] = count($data['nos']);

            if(isset($total[$v])){
                $data['count'] = $total[$v];
            }else{
                $data['count'] = 0;
            }
            
            $datas[] = $data;
            # code...
        }

        $sort = array_column($datas,'count');
        array_multisort($sort,SORT_DESC,$datas);
        return ['type'=>'success','data'=>$datas];
    }

    //库存sku盘点
    public function AddCustomSkuCount($params){

        $data = $params['data'];
        if(!isset($params['location_code'])){
            return['type'=>'fail','msg'=>'无库位编码'];
        }
        if(!isset($params['warehouse_id'])){
            return['type'=>'fail','msg'=>'无仓库id'];
        }
        if(!isset($params['user_id'])){
            return['type'=>'fail','msg'=>'无用户id'];
        }

        $location = db::table('cloudhouse_warehouse_location')->where('warehouse_id',$params['warehouse_id'])->where('location_code',$params['location_code'])->first();

        if(!$location){
            return['type'=>'fail','msg'=>'该仓库无此库位编码,仓库id:'.$params['warehouse_id'].'库位编码:'.$params['location_code']];
        }
        $location_code = $params['location_code'];
        $user_id = $params['user_id'];
        $warehouse_id = $params['warehouse_id'];
        $time = date('Y-m-d H:i:s',time());
        $day = date('Y-m-d',time());
        $no = 1;
        $res = db::table("custom_sku_count")->where('create_time','like','%'.$day.'%')->where('user_id',$user_id)->where('is_del',0)->orderby('no','desc')->first();
        if($res){
            $no = $res->no+1;
        }


        $isExist     = [];
        $skuData     = [];
        $i           = 0;
        $type_detail = $params['type_detail'];
        foreach ($data as $dv) {
            $customSkuInfo = DB::table('self_custom_sku')
                ->where('custom_sku', $dv['custom_sku'])
                ->orWhere('old_custom_sku', $dv['custom_sku'])
                ->first();
            if (!$customSkuInfo) continue;

            $isExist[] = $dv['custom_sku'];

            $skuData[$i]['custom_sku'] = $dv['custom_sku'];
            $skuData[$i]['num']        = $dv['num'];
            if ($type_detail == 3) {
                $skuData[$i]['location_id'] = $location->id;
            } else {
                $skuData[$i]['location_data']['0']['location_id'] = $location->id;
                $skuData[$i]['location_data']['0']['platform_id'] = 4;
                $skuData[$i]['location_data']['0']['num']         = $dv['num'];
            }
            $i++;
            # code...
        }

        if ($skuData) {
            $remark = $params['remark'] ?? ($params['remark'] ?: ($type_detail == 3 ? '盘点入库' : '盘点出库'));
            $instore['skuData']     = $skuData;
            $instore['type_detail'] = $type_detail;//3:手工入库 11:手工出库
            $instore['type']        = 5;
            if ($type_detail == 3) {
                $instore['in_house'] = $warehouse_id;
            } elseif ($type_detail == 11) {
                $instore['out_house'] = $warehouse_id;
            }
            $instore['remark']      = $remark;
            $instore['platform_id'] = 4;
            $instore['token']       = $params['token'];

            $model = new InventoryModel();
            $res   = $model->goods_transfers($instore);

            if ($res['code'] == 500) {
                return ['type' => 'fail', 'msg' => $res['msg']];
            }
        }


        foreach ($data as $v) {
            # code...
            $insert['custom_sku'] =  $v['custom_sku'];
            $insert['no'] = $no;
            $insert['create_time'] = $time;
            $insert['custom_sku_id'] = $v['custom_sku_id'];
            $insert['count'] =$v['num'];
            $insert['location_code'] = $location_code;
            $insert['user_id'] = $user_id;
            $insert['warehouse_id'] = $warehouse_id;
            $insert['is_instore'] = in_array($v['custom_sku'], $isExist) ? 1 : 0;
            db::table('custom_sku_count')->insert($insert);
            // $is_count = db::table('custom_sku_count')->where('custom_sku',$v['custom_sku'])->where('create_time',$time)->first();
    
            // if($is_count){
            //     db::table('custom_sku_count')->where('id',$is_count->id)->update($insert);
            // }else{
            //     db::table('custom_sku_count')->insert($insert);
            // }
            
        }

        return['type'=>'success','data'=>''];
    }

    //fasin新增 修改
    public function CreateFasin($params){

        $fasinList = explode(',', $params['fasin']);

        foreach ($fasinList as $fasin) {
            # code...
            if(!empty($fasin)){
                $is_self = $params['is_self']??1;
                // if($is_self==1){
                //     $is_in = db::table('self_sku')->where('fasin',$fasin)->first();
                //     if(!$is_in){
                //         return ['type'=>'fail','msg'=>'添加失败,无此fasin对应sku']; 
                //     }
                // }
            
                $res = db::table('amazon_fasin')->where('fasin',$fasin)->first();
                $query['fasin'] =  $fasin;
                $query['is_self'] = $is_self;
                if(isset($params['type'])){
                    $query['type'] = $params['type'];
                }
                if(isset($params['one_cate_id'])){
                    $query['one_cate_id'] = $params['one_cate_id'];
                }
                if(isset($params['two_cate_id'])){
                    $query['two_cate_id'] = $params['two_cate_id'];
                }
                if(isset($params['three_cate_id'])){
                    $query['three_cate_id'] = $params['three_cate_id'];
                }
                if(isset($params['user_id'])){
                    $query['user_id'] = $params['user_id'];
                }
                if(isset($params['shops'])){
                    $query['shops'] = $params['shops'];
                }
                if ($is_self==1){
                    db::beginTransaction();
                    try {
                        if($res){
                            db::table('amazon_fasin')->where('fasin',$fasin)->update($query);
                        }else{
                            db::table('amazon_fasin')->insert($query);
                            if ($is_self == 1){
                                // 保存链接代号
                                $shopIds = explode(',', $params['shops']);
        //                $fasinCodeMdl = DB::table('amazon_fasin_bind')->where('fasin', $faisn)->whereIn('shop_id', $shopIds)->get();
                                foreach ($shopIds as $shopId){
                                    $fasinBind = db::table('amazon_fasin_bind')->where('shop_id', $shopId)->orderBy('fasin_code', 'DESC')->first();
                                    $shop = Db::table('shop')->where('id', $shopId)->first();
                                    if (empty($shop) || empty($shop->identifying)){
                                        throw new \Exception("店铺信息不存在或未绑定店铺标识!");
                                    }
                                    $shop = $shop->identifying;
                                    if ($fasinBind){
                                        $no = preg_replace('/\D/','', $fasinBind->fasin_code);
                                        $code = (int)$no+1;
                                        $code = str_pad($code, 2, '0',STR_PAD_LEFT);
                                        $fasinCode = $shop.$code;
                                    }else{
                                        $fasinCode = $shop."01";
                                    }
                                    db::table('amazon_fasin_bind')->insert(['fasin' => $fasin, 'shop_id' => $shopId, 'fasin_code' => $fasinCode]);
                                }
                            }
                        }

                    }catch (\Exception $e){
                        db::rollback();
                        return ['type'=>'fail','msg'=>'请求失败,错误原因：'.$e->getMessage().'; 错误位置：'.$e->getLine()];
                    }
                }else{
                    $query['shop_name'] = $params['shop_name']??'';
                    $query['memo'] = $params['memo']??'';
                    if($res){
                        db::table('amazon_fasin')->where('fasin',$fasin)->update($query);
                    }else{
                        db::table('amazon_fasin')->insert($query);
                    }
                }
            }
        }
       
        db::commit();
        return ['type'=>'success','msg'=>'请求成功'];
       
    }

    //fasin表删除
    public function DelFasin($params){

        $fasins = $params['fasin'];

        foreach ($fasins as $fasin) {
            $insert['type']=4;
            $insert['name']=$fasin;
            $insert['user_id']=$params['user_id'];
            $insert['create_time'] = time();
            $del = db::table('amazon_fasin')->where('fasin',$fasin)->delete();
            if($del){
                //加入日志
                db::table('self_del_log')->insert($insert);
            }
        }
      
        return ['type'=>'success','msg'=>'删除成功'];
    }


    public function CreateFasin_b($param){


        $f_list = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->groupby('a.fasin')->select('a.fasin','b.user_id')->get();

        foreach ($f_list as $v) {
            # code...
               //品名
              
                   $fasin =  $v->fasin;

                   $v->one_cate_id = 0;
                   $v->two_cate_id = 0;
                   $v->three_cate_id = 0;
  
                   $spus = Db::table('self_sku as a')->leftjoin('self_spu as b','a.spu_id','=','b.id')->where('a.fasin',$fasin)->select('a.sku','b.spu','b.type','b.one_cate_id','b.two_cate_id','b.three_cate_id','a.shop_id','b.id as spu_id')->get();
                   $zspus = [];
                   $zvspu = [];
                   foreach ($spus as $sv) {
                       # code...
                     //   if($sv->shop_id>0){
                     //      $shopname = $this->GetShop($sv->shop_id)['shop_name'];
                     //   }
      
                       if($sv->one_cate_id>0){
                            $v->one_cate_id = $sv->one_cate_id;
                            $v->two_cate_id = $sv->two_cate_id;
                            $v->three_cate_id = $sv->three_cate_id;
                       }elseif($sv->type==2){
                           $zspus = Db::table('self_group_spu')->where('spu_id',$sv->spu_id)->get();
                           foreach ($zspus as $zv) {
                               # code...
                               $zvspu = Db::table('self_spu')->where('id',$zv->group_spu_id)->first();
                               if(!empty($zvspu)){
                                   if($zvspu->one_cate_id>0){
                                    $v->one_cate_id = $zvspu->one_cate_id;
                                    $v->two_cate_id = $zvspu->two_cate_id;
                                    $v->three_cate_id = $zvspu->three_cate_id;
                                   }
                               }
     
                           }
                       }
                   }
  


            $cus = db::table('self_sku')->where('fasin',$v->fasin)->groupby("shop_id")->select("shop_id")->get()->toArray();
           
            $v->shops = implode(',',array_column($cus,'shop_id'));

            $params = json_decode(json_encode($v),true);

            $fasin = $params['fasin'];
            $res = db::table('amazon_fasin')->where('fasin',$fasin)->first();
            $query['fasin'] =  $fasin;
            if(isset($params['type'])){
                $query['type'] = $params['type'];
            }
            if(isset($params['one_cate_id'])){
                $query['one_cate_id'] = $params['one_cate_id'];
            }
            if(isset($params['two_cate_id'])){
                $query['two_cate_id'] = $params['two_cate_id'];
            }
            if(isset($params['three_cate_id'])){
                $query['three_cate_id'] = $params['three_cate_id'];
            }
            if(isset($params['user_id'])){
                $query['user_id'] = $params['user_id'];
            }
            if(isset($params['shops'])){
                $query['shops'] = $params['shops'];
            }
    
            if($res){
                db::table('amazon_fasin')->where('fasin',$fasin)->update($query);
            }else{
                db::table('amazon_fasin')->insert($query);
            }
    
            // return ['type'=>'success','msg'=>'请求成功'];
   
        }


        return ['type'=>'success','msg'=>'请求成功'];

      
    }

   

    public function GetFasins($fasins,$start_time,$end_time,$shop_id){


        $skus = db::table('self_sku')->whereIn('fasin',$fasins);
        if($shop_id>0){
            $skus = $skus->where('shop_id',$shop_id);
        }
        
        $skus = $skus->get()->toArray();

        $sku_ids = array_column($skus,'id');

                // DB::connection()->enableQueryLog();

        $orders = db::table('amazon_order_item')->whereBetween('amazon_time', [$start_time, $end_time])->where('order_status','!=','Canceled')->whereIn('sku_id',$sku_ids)->select('sku_id','quantity_ordered')->get();
        // print_r(DB::getQueryLog());
        $order_r = [];
        foreach ($orders as $v) {
            # code...
            if(isset($order_r[$v->sku_id])){
                $order_r[$v->sku_id] += $v->quantity_ordered;
            }else{
                $order_r[$v->sku_id] = $v->quantity_ordered;
            }
             
        }

        $product_r = [];
        $products = db::table('product_detail')->whereIn('sku_id',$sku_ids)->select('sku_id','in_stock_num','in_bound_num','transfer_num')->get();

        foreach ($products as $v) {
            # code...
            $product_r[$v->sku_id] = json_decode(json_encode($v),true);
        }

        $return_r = [];
        $return =  Db::table('amazon_return_order')->whereIn('sku_id',$sku_ids)->whereBetween('return_date', [$start_time, $end_time])->select('sku_id','quantity')->get();

        foreach ($return as $v) {
            # code...
            if(isset($return_r[$v->sku_id])){
                $return_r[$v->sku_id] += $v->quantity;
            }else{
                $return_r[$v->sku_id] = $v->quantity;
            }
        }

        $nsku = [];
        foreach ($skus as $sv) {
            # code...
            $nsku[$sv->fasin] = 1;
     
        }

        $unfasin = [];
        foreach ($fasins as $fv) {
            if(!isset($nsku[$fv])){
                $unfasin[] = $fv;
            }
        }



        foreach ($skus as $v) {
            # code...

            $sku_id = $v->id;

            $v->order_num = 0;
            if(isset($order_r[$sku_id])){
                $v->order_num = $order_r[$sku_id];
            }

            $v->return_num = 0;
            if(isset($return_r[$sku_id])){
                $v->return_num = $return_r[$sku_id];
            }

            $v->in_stock_num = 0;
            $v->in_bound_num = 0;
            $v->transfer_num = 0;


            if(isset($product_r[$sku_id])){
                $v->in_stock_num = $product_r[$sku_id]['in_stock_num'];
                $v->in_bound_num = $product_r[$sku_id]['in_bound_num'];
                $v->transfer_num = $product_r[$sku_id]['transfer_num'];
            }

            $total_inventory = $v->in_stock_num+$v->in_bound_num+$v->transfer_num;
            if($total_inventory==0){
                $v->img = '';
            }else{
                $v->img = $this->GetCustomskuImg($v->custom_sku);
            }

            $v->return_rate = 0;
            if($v->return_num>0&&$v->order_num>0){
                $v->return_rate = round($v->return_num/$v->order_num*100,2);
            }

           
        }

        // $imgs = [];

        // foreach ($cusres as $cus => $value) {
        //     # code...
        //     $imgs[$cus] = $this->GetCustomskuImg($cus);
        // }
        // var_dump($skus);
        // return $skus;
        $return = [];


        foreach ($skus as $v) {
            # code...
            $fasin = $v->fasin;
            $return[$fasin]['fasin'] = $fasin;

            $skures['sku'] = $v->sku;
            $skures['asin'] = $v->asin??'';
            $skures['img'] = $v->img;
            $skures['sku_id'] = $v->id;
            $skures['order_num'] = $v->order_num;
            $skures['return_num'] = $v->return_num;
            $skures['in_stock_num'] = $v->in_stock_num;
            $skures['transfer_num'] = $v->transfer_num;
            $skures['in_bound_num'] = $v->in_bound_num;
            $skures['return_rate'] = $v->return_rate;



            $return[$fasin]['skus'][] = $skures;
  


            // if(isset($imgs[$v->custom_sku])){
            //     $return[$fasin]['imgs'][$v->custom_sku] = $imgs[$v->custom_sku];
            // }
            
            if(isset($return[$fasin]['order_num'])){
                $return[$fasin]['order_num'] +=$v->order_num;
            }else{
                $return[$fasin]['order_num'] =$v->order_num;
            }
            if(isset($return[$fasin]['return_num'])){
                $return[$fasin]['return_num'] +=$v->return_num;
            }else{
                $return[$fasin]['return_num'] =$v->return_num;
            }
            if(isset($return[$fasin]['in_stock_num'])){
                $return[$fasin]['in_stock_num'] +=$v->in_stock_num;
            }else{
                $return[$fasin]['in_stock_num'] =$v->in_stock_num;
            }
            if(isset($return[$fasin]['transfer_num'])){
                $return[$fasin]['transfer_num'] +=$v->transfer_num;
            }else{
                $return[$fasin]['transfer_num'] =$v->transfer_num;
            }
            if(isset($return[$fasin]['in_bound_num'])){
                $return[$fasin]['in_bound_num'] +=$v->in_bound_num;
            }else{
                $return[$fasin]['in_bound_num'] =$v->in_bound_num;
            } 
        }
   

        foreach ($unfasin as $uf) {
            # code...
            $fasin = $uf;
            $return[$fasin]['fasin'] = $uf;
            $return[$fasin]['skus'][] = [];
            $return[$fasin]['order_num'] = 0;
            $return[$fasin]['return_num'] = 0;
            $return[$fasin]['in_stock_num'] = 0;
            $return[$fasin]['transfer_num'] = 0;
            $return[$fasin]['in_bound_num'] = 0;
        }

        return $return;
    }


    public function GetFainimgs($fasin){
       $res =db::table('self_sku')->where('fasin',$fasin)->groupby('custom_sku')->select('custom_sku')->get();
    
       $imgs = [];
       foreach ($res as $v) {
        # code...
            $img = $this->GetCustomskuImg($v->custom_sku);

            if(!empty($img)){
                $imgs[$img] = $img;
            }
       }

       $imgs = array_values($imgs);
       return $imgs;
    }


    public function DatawholeSku($params){
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }

        $list = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku_id','=','sc.id')->leftjoin('self_spu as sp','sp.id','=','sc.spu_id');

        $totalNum = Db::table('self_sku as sk')->leftjoin('self_custom_sku as sc','sk.custom_sku_id','=','sc.id')->leftjoin('self_spu as sp','sp.id','=','sc.spu_id');

        if(isset($params['sku'])){
            $list = $list->where(function($query) use($params){
                    $query->Where('sk.sku','like','%'.$params['sku'].'%')->orWhere('sk.old_sku','like','%'.$params['sku'].'%');
                });
            $totalNum =  $totalNum->where(function($query) use($params){
                $query->Where('sk.sku','like','%'.$params['sku'].'%')->orWhere('sk.old_sku','like','%'.$params['sku'].'%');
            });
        }
        if(isset($params['custom_sku'])){
            $list = $list->where(function($query) use($params){
                $query->Where('sc.custom_sku','like','%'.$params['custom_sku'].'%')->orWhere('sc.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
            $totalNum =  $totalNum->where(function($query) use($params){
                $query->Where('sc.custom_sku','like','%'.$params['custom_sku'].'%')->orWhere('sc.old_custom_sku','like','%'.$params['custom_sku'].'%');
            });
        }
        if(isset($params['spu'])){
            $list = $list->where(function($query) use($params){
                $query->Where('sp.spu','like','%'.$params['spu'].'%')->orWhere('sp.old_spu','like','%'.$params['spu'].'%');
            });
            $totalNum =  $totalNum->where(function($query) use($params){
                $query->Where('sp.spu','like','%'.$params['spu'].'%')->orWhere('sp.old_spu','like','%'.$params['spu'].'%');
            });
        }
        if(isset($params['color'])){
            $list = $list->where('sc.color',$params['color']);
            $totalNum =  $totalNum->where('sc.color',$params['color']);
        }


        $list = $list
        ->leftjoin('self_color_size as cz','sc.size','=','cz.identifying')
        ->orderby('sk.shop_id','ASC')
        ->orderby('sc.color','ASC')
        ->orderby('cz.sort','ASC')
        ->offset($pagenNum)->limit($limit)
        ->select('sk.id as sku_id','sk.sku','sk.shop_id','sk.user_id','sk.old_sku','sc.custom_sku','sc.id as custom_sku_id','sc.old_custom_sku','sc.size','sc.color','sp.id as spu_id','sp.spu','sp.old_spu','sp.one_cate_id','sp.three_cate_id')
        ->get()->toArray();




        $totalNum =  $totalNum->count();

        $newdata = [];
        $i = 0;

        $sessions_total = [];
        $s_time = $params['start_time']??date('Y-m-d',time());
        $e_time = $params['end_time']??date('Y-m-d',time());

        // if(isset($params['start_time'])&&isset($params['end_time'])){
        $nsku =  array_column($list, 'sku');
        $osku =  array_column($list, 'old_sku');
        $skus = array_merge( $nsku, $osku);
        $start = $s_time.' 00:00:00';
        $end = $e_time.' 23:59:59';
        // $returns = Db::table('amazon_sale_percentage')->whereIn('sku',$skus)->whereBetween('ds', [$start, $end])->get();
        // $return_arr = [];
        // foreach ($returns as $rv) {
        //     # code...
        //     $return_arr[$rv->sku] += $rv->session_percentage;
        // }


        $sku_ids = array_column($list,'sku_id');
        //会话率查询
        $sessions_total = [];
        $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start, $end])->whereIn('sku_id',$sku_ids)->where('sessions_total','>',0)->groupby('sku_id')->select('sku_id',db::raw('sum(sessions_total) as sessions_total'))->get();
    
        foreach ($sessions_res as $srv) {
            # code...
            $sessions_total[$srv->sku_id] = $srv->sessions_total;
        }


        $product = DB::table('product_detail')->whereIn('sku_id',$sku_ids)->get();
        $p_arr = [];
        foreach ($product as $pv) {
            # code...
            $p_arr[$pv->sku_id]['in_stock_num'] = $pv->in_stock_num??0;
            $p_arr[$pv->sku_id]['transfer_num'] = $pv->transfer_num??0;
            $p_arr[$pv->sku_id]['in_bound_num'] = $pv->in_bound_num??0;
        }

        $orders = [];
        $order_num = Db::table('amazon_order_item')->whereIn('sku_id',$sku_ids)->whereBetween('amazon_time', [$start, $end])->select('sku_id','quantity_ordered')->get();
 



        foreach ($order_num as $ov) {
            # code...
            if(isset($orders[$ov->sku_id])){
                $orders[$ov->sku_id]+=$ov->quantity_ordered;
            }else{
                $orders[$ov->sku_id]=$ov->quantity_ordered;
            }

        }



        $returns = [];
        $return_num = Db::table('amazon_return_order')->whereIn('sku_id',$sku_ids)->whereBetween('return_date', [$start, $end])->select('sku_id','quantity')->get();
        foreach ($return_num as $rv) {
            # code...
            if(isset($returns[$rv->sku_id])){
                $returns[$rv->sku_id]+=$rv->quantity;
            }else{
                $returns[$rv->sku_id]=$rv->quantity;
            }

        }

        // $sales_num = Db::table('amazon_sale_percentage')->whereIn('sku',$sku)->whereBetween('ds', [$start_time, $end_time])->sum('session_percentage');
        // }
        // $return_arr = [];
        foreach ($list as $v) {
            # code...
            // $skuinfo = [];
        //    $skuinfo =  Redis::Hget('datacache:go-sku-info',$v->sku);
        //    if($skuinfo){
        //         $skuinfo = json_decode($skuinfo,true);

        //         $skuinfo['sessions_total'] = 0;
        //         if(isset($sessions_total[$v->id])){
        //             $skuinfo['sessions_total'] = $sessions_total[$v->id];
        //         }


        //         $skuinfo['old_sku'] =  $v->old_sku??'';
        //         $skuinfo['custom_sku'] =  $v->custom_sku;
        //         $skuinfo['old_custom_sku'] =  $v->old_custom_sku??'';
        //         $skuinfo['spu'] =  $v->spu;
        //         $skuinfo['old_spu'] =  $v->old_spu??'';
        //         $skuinfo['color'] = $v->color;

        //         if (isset($params['start_time'])&&isset($params['end_time'])) {
        //             $start = $params['start_time'] . ' 00:00:00';
        //             $end = $params['end_time'] . ' 23:59:59';
        //             $query['sku'][0] = $v->sku;
        //             if($v->old_sku){
        //                 $query['sku'][1] = $v->old_sku;
        //             }
        //             $query['start_time'] = $start;
        //             $query['end_time'] = $end;
        //             $skuinfo['order_num'] = $this->getOrderNum($query);
        //             $skuinfo['return_num'] =  $this->getReturnNum($query);
        //             // $skuinfo['sales_num'] =  $this->getSalesNum($query);

        //             if($v->old_sku){
        //                 if (array_key_exists($v->old_sku, $return_arr)) {
        //                     $skuinfo['sales_num'] = $return_arr[$v->old_sku];
        //                 }
        //             }
        //             if (array_key_exists($v->sku, $return_arr)) {
        //                 $skuinfo['sales_num'] = $return_arr[$v->sku];
        //             }
        //         }

        //         //转化率
        //         $skuinfo['conversion_rate'] = 0;
        //         $skuinfo['return_rate'] = 0;
        //         if($skuinfo['order_num']>0){
        //             // if($skuinfo['sales_num']>0){
        //             //     $skuinfo['conversion_rate'] =  round($skuinfo['sales_num']/$skuinfo['order_num'], 4) * 100;
        //             // }

        //             if($skuinfo['sessions_total']>0){
        //                 $skuinfo['conversion_rate'] = round(($skuinfo['order_num']/$skuinfo['sessions_total'])*100,2);
        //                 $skuinfo['conversion_rate_e'] = $skuinfo['conversion_rate'].'%';
        //              }

        //             //退货率
        //             if($skuinfo['return_num']>0){
        //                 $skuinfo['return_rate'] =  round( $skuinfo['return_num']/ $skuinfo['order_num'], 4) * 100;
        //             }
        //         }

        //    }else{

                $skuinfo['sessions_total'] = 0;
                if(isset($sessions_total[$v->sku_id])){
                    $skuinfo['sessions_total'] = $sessions_total[$v->sku_id];
                }
                $skuinfo['name'] =  $this->GetCategory($v->one_cate_id)['name'].$this->GetCategory($v->three_cate_id)['name'];
                $skuinfo['sku'] =  $v->sku;
                $skuinfo['old_sku'] =  $v->old_sku??'';
                $skuinfo['custom_sku'] =  $v->custom_sku;
                $skuinfo['old_custom_sku'] =  $v->old_custom_sku??'';
                $skuinfo['spu'] =  $v->spu;
                $skuinfo['old_spu'] =  $v->old_spu??'';
                $skuinfo['color'] = $v->color;
                $skuinfo['size'] = $v->size;
                $skuinfo['user_name'] = $this->GetUsers($v->user_id)['account'];
                // $product = DB::table('product_detail')->where('sellersku',$v->sku);
                // if($v->old_sku){
                //     $product = $product ->orwhere('sellersku',$v->old_sku);
                // }

                // $product = $product->first();

                // $skuinfo['in_stock_num'] = $product->in_stock_num??0;
                // $skuinfo['transfer_num'] = $product->transfer_num??0;
                // $skuinfo['in_bound_num'] = $product->in_bound_num??0;

                // $p_arr[$pv->sku_id]['in_stock_num'] = $pv->in_stock_num??0;
                // $p_arr[$pv->sku_id]['transfer_num'] = $pv->transfer_num??0;
                // $p_arr[$pv->sku_id]['in_bound_num'] = $pv->in_bound_num??0;

                $skuinfo['in_stock_num'] = 0;
                $skuinfo['transfer_num'] = 0;
                $skuinfo['in_bound_num'] = 0;

                if(isset($p_arr[$v->sku_id])){
                    $skuinfo['in_stock_num'] = $p_arr[$v->sku_id]['in_stock_num'];
                    $skuinfo['transfer_num'] = $p_arr[$v->sku_id]['transfer_num'];
                    $skuinfo['in_bound_num'] = $p_arr[$v->sku_id]['in_bound_num'];

                }
                $skuinfo['shop_id'] = $v->shop_id;
                $skuinfo['shop_name'] = $this->GetShop($skuinfo['shop_id'])['shop_name']??'';

                $query['sku'][0] = $v->sku;
                if($v->old_sku){
                    $query['sku'][1] = $v->old_sku;
                }


                $skuinfo['sales_num'] = 0;
                // if (isset($params['start_time'])&&isset($params['end_time'])) {
                //     $start = $params['start_time'] . ' 00:00:00';
                //     $end = $params['end_time'] . ' 23:59:59';
                //     if($v->old_sku){
                //         if (array_key_exists($v->old_sku, $return_arr)) {
                //             $skuinfo['sales_num'] = $return_arr[$v->old_sku];
                //         }
                //     }
                //     if (array_key_exists($v->sku, $return_arr)) {
                //         $skuinfo['sales_num'] = $return_arr[$v->sku];
                //     }
                // }else{
                //     $start = date('Y-m-d',time()-3600*24*7) . ' 00:00:00';
                //     $end = date('Y-m-d',time()). ' 23:59:59';
                    // $query['start_time'] = $start;
                    // $query['end_time'] = $end;
                    // $skuinfo['sales_num'] =  $this->getSalesNum($query);
                // }
              
                $query['start_time'] = $start;
                $query['end_time'] = $end;

        
                $skuinfo['order_num']  = 0;
                if(isset($orders[$v->sku_id])){
                    $skuinfo['order_num'] = $orders[$v->sku_id];
                }
                

                $skuinfo['return_num']  = 0;
                if(isset($returns[$v->sku_id])){
                    $skuinfo['return_num'] = $returns[$v->sku_id];
                }
                // $skuinfo['order_num'] = $this->getOrderNum($query);
                // $skuinfo['return_num'] =  $this->getReturnNum($query);


                //转化率
                $skuinfo['conversion_rate'] = 0;
                $skuinfo['return_rate'] = 0;
                if($skuinfo['order_num']>0){
                    if($skuinfo['sessions_total']>0){
                        $skuinfo['conversion_rate'] = round(($skuinfo['order_num']/$skuinfo['sessions_total'])*100,2);
                        $skuinfo['conversion_rate_e'] = $skuinfo['conversion_rate'].'%';
                     }

                    //退货率
                    if($skuinfo['return_num']>0){
                        $skuinfo['return_rate'] =  round($skuinfo['return_num']/$skuinfo['order_num'], 4) * 100;
                    }
                }

                $skuinfo['img'] = $this->GetCustomskuImg($v->custom_sku_id);
        //    }
           $newdata[$i] = $skuinfo;
           $i++;
        }



        return ['data' => $newdata,'totalnum' => $totalNum];

    }


    public function getReturnNum($params){
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $sku =  $params['sku'];
        $num = Db::table('amazon_return_order')->whereIn('sku',$sku)->whereBetween('return_date', [$start_time, $end_time])->sum('quantity');
        return $num;
    }
    public function getOrderNum($params){
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $sku =  $params['sku'];
        $num = Db::table('amazon_order_item')->whereIn('seller_sku',$sku)->whereBetween('amazon_time', [$start_time, $end_time])->sum('quantity_ordered');
        return $num;
    }
    public function getSalesNum($params){
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $sku =  $params['sku'];
        $num = Db::table('amazon_sale_percentage')->whereIn('sku',$sku)->whereBetween('ds', [$start_time, $end_time])->sum('session_percentage');
        return $num;
    }



    public function DatawholeSpuColor($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }


        $type =  isset($params['types']) ? $params['types'] : 1;
        switch ($type) {
            case 1:
                # code...
                //当日
                $table = 'cache_cus_today';
                $day = 1;
                $start_time = date('Y-m-d 00:00:00',time());
                $end_time = date('Y-m-d 23:59:59',time());
                break;
            case 2:
                # code...
                //昨日
                $table = 'cache_cus_yestoday';
                $day = 1; 
                $start_time = date('Y-m-d 00:00:00',time()-86400);
                $end_time = date('Y-m-d 23:59:59',time()-86400);
                break;
            case 3:
                # code...
                //七天
                $table = 'cache_cus_week';
                $day = 7;
                $start_time = date('Y-m-d 00:00:00',time()-(86400*7));
                $end_time = date('Y-m-d 23:59:59',time());
                break;
            case 4:
                # code...
               //十四天
               $table = 'cache_cus_tweek';
               $day = 14;
               $start_time = date('Y-m-d 00:00:00',time()-(86400*14));
               $end_time = date('Y-m-d 23:59:59',time());
               break;
            case 5:
                # code...
               //一月
               $table = 'cache_cus_moon';
               $day = 30;
               $start_time = date('Y-m-d 00:00:00',time()-(86400*30));
               $end_time = date('Y-m-d 23:59:59',time());
               break;
            default:
                # code...
                break;
        }
        
    
        //初始化查询
        $thisDb = Db::table($table.' as a')->leftjoin('self_custom_sku as b','b.id','=','a.custom_sku_id')->leftjoin('self_spu as c','c.id','=','b.spu_id');
        if (isset($params['custom_sku'])) {
            $thisDb = $thisDb->where('b.custom_sku','like','%'.$params['custom_sku'].'%')->orWhere('b.old_custom_sku','like','%'.$params['custom_sku'].'%');
        }
        if (isset($params['spu_id'])) {
            $thisDb = $thisDb->where('b.spu_id',$params['spu_id']);
        }else if(!isset($params['spu'])) {
            $thisDb = $thisDb->where('b.spu_id',384);
        }
        if (isset($params['spu'])) {

            $thisDb = $thisDb->where(function($query) use($params){
                $query->where('c.spu','like','%'.$params['spu'].'%')->orWhere('c.old_spu','like','%'.$params['spu'].'%');
            });
            // $thisDb = $thisDb->where('c.spu','like','%'.$params['spu'].'%')->orWhere('c.old_spu','like','%'.$params['spu'].'%');
        }
        $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';

        $totalNum=$thisDb->groupby('b.color')->get()->count();

  
        // DB::connection()->enableQueryLog();


            // ->offset($pagenNum)
            // ->limit($limit)
            $list = $thisDb
            ->select('a.update_time',db::raw('group_concat(b.id) as cus_ids'),'c.id','c.spu','b.color','b.color_id','c.old_spu',DB::raw('GROUP_CONCAT(b.custom_sku) as custom_sku'),DB::raw('sum(a.session_percentage) as session_percentage'),DB::raw('sum(a.return_num) as return_num'),DB::raw('sum(a.order_num) as order_num'),DB::raw('sum(a.in_stock_num) as in_stock_num'),DB::raw('sum(a.transfer_num) as transfer_num'),DB::raw('sum(a.in_bound_num) as in_bound_num'),DB::raw('sum(a.quanzhou_num) as quanzhou_num'),DB::raw('sum(a.tongan_num) as tongan_num'),DB::raw('sum(a.cloud_num) as cloud_num'),DB::raw('sum(a.factory_num) as factory_num'),DB::raw('sum(a.shipment_order_num) as shipment_order_num'),DB::raw('sum(a.out_order_num) as out_order_num'),DB::raw('sum(a.tongan_request_num) as tongan_request_num'),DB::raw('sum(a.quanzhou_request_num) as quanzhou_request_num'),DB::raw('sum(a.cloud_request_num) as cloud_request_num'),DB::raw('sum(a.courier_num) as courier_num'),DB::raw('sum(a.shipping_num) as shipping_num'),DB::raw('sum(a.air_num) as air_num'),DB::raw('sum(a.no_shipment_num) as no_shipment_num'),DB::raw('round(AVG(return_rate),2) as return_rate'),DB::raw('round(AVG(conversion_rate),2) as conversion_rate'))
            ->orderby($orderby,$orderbytype)
            ->groupby('b.color')
            ->get();

        $today = date('Y-m-d',time());
        $todaycache = Db::table('cache_cus_today')->where('ds','like',$today.'%')->first();
        $new_update_time = $today; 
        if($todaycache){
            $new_update_time  = $todaycache->update_time;
        }
           
        $report_spu_color = [];
        $report_spu_colors =Db::table('self_spu_color_isplace')->get();
        foreach ($report_spu_colors as $report_v) {
            # code...
            $rekey = $report_v->spu_id.'-'.$report_v->color_id;
            $report_spu_color[$rekey] = 1;
        }
        // var_dump(DB::getQueryLog());

          //
          $total_order = 0;
          $total_return = 0;
          $total_inventory_quanzhou = 0;
          $total_inventory_tongan = 0;
          $total_cloud_tongan = 0;
          $total_in_stock_num = 0;
          $total_transfer_num = 0;
          $total_in_bound_num = 0;
          $total_tongan_request_num = 0;
          $total_quanzhou_request_num = 0;
          $total_cloud_request_num = 0;
          $total_courier_num = 0;//计划快递发货
          $total_shipping_num = 0;//计划海运发货
          $total_air_num = 0;//计划空运发货
  
          $total_shipment_order_num = 0; //生产下单数据
          $total_out_order_num = 0; //已出货
          $total_tongan_deduct_inventory = 0;
          $total_quanzhou_deduct_inventory = 0;
          $total_cloud_deduct_inventory = 0;
  
          $total_inventory = 0;

        $cus_ids = [];
        foreach ($list as $v) {
            # code...
                $cus_ids = array_merge($cus_ids,explode(',',$v->cus_ids));
                // if(!isset($new_update_time)){
                //     $new_update_time = $v->update_time;
                // }
                $v->report_spu_color = 0;
                $spu_color_report_key = $v->id.'-'.$v->color_id;
                if(isset($report_spu_color[$spu_color_report_key])){
                    $v->report_spu_color = 1;
                }
                //预减后库存
                $v->tongan_deduct_inventory = $v->tongan_num - $v->tongan_request_num;
                $v->quanzhou_deduct_inventory = $v->quanzhou_num - $v->quanzhou_request_num;
                $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;

                $v->day_quantity_ordered = round($v->order_num/$day,2);
                //补货提醒 - 本地
                //1 需要下单  2 偏多  3 冗余
                $buhuo_status_bd = 0;

                $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
                //fba仓库存
                $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
                //本地仓库存
    

                $v->here_inventory_day = 0;
                $v->fba_inventory_day = 0;
                if($v->here_inventory>0&&$v->day_quantity_ordered>0){
                    $v->here_inventory_day = round(($v->here_inventory/$v->day_quantity_ordered),2);
                }

                if($v->fba_inventory>0&&$v->day_quantity_ordered>0){
                    $v->fba_inventory_day = round(($v->fba_inventory/$v->day_quantity_ordered),2);
                }

                
                $bdzz = $v->here_inventory_day;
                if ($bdzz >= 0 && $bdzz < 60) {
                    $buhuo_status_bd = 1;
                }
                if ($bdzz >= 60 && $bdzz < 90) {
                    $buhuo_status_bd = 2;
                }
                if ($bdzz > 90) {
                    $buhuo_status_bd = 3;
                }

                $fbazz =  $v->fba_inventory_day;

                $buhuo_status_fba = 0; 
                //补货提醒更新
                if ($fbazz >= 0 && $fbazz < 60) {
                    $buhuo_status_fba = 1;
                }
                if ($fbazz >= 60 && $fbazz < 90) {
                    $buhuo_status_fba = 2;
                }
                if ($fbazz > 90) {
                    $buhuo_status_fba = 3;
                }

                $v->buhuo_status_bd = $buhuo_status_bd; 
                $v->buhuo_status_fba = $buhuo_status_fba; 

                //补货状态  1补货过多 近两周日销*60<计划补货数量
                
                // s_day_quantity_ordered
                $v->send_status = 0;

                $courier_num  = 0;
                $shipping_num = 0;
                $air_num = 0;

                if(isset($v->courier_num)){
                    $courier_num = (int)$v->courier_num;
                }

                if(isset($v->shipping_num)){
                    $shipping_num = (int)$v->shipping_num;
                }
                if(isset($v->air_num)){
                    $air_num = (int)$v->air_num;
                }

                $jh_buhuo = $courier_num+$shipping_num+$air_num;
                //计划发货
                if($jh_buhuo>$v->day_quantity_ordered*60){
                    $v->send_status = 1;
                }


                //下单状态  1下单过多 近两周日销*45<未出货数量
                $v->place_order_status = 0;
                
                if($v->no_shipment_num>$v->day_quantity_ordered*45){
                    $v->place_order_status = 1;
                }
              

                // if($v->old_custom_sku){
                //     $v->custom_sku = $v->old_custom_sku;
                // }

                $base_spu_id = $this->GetBaseSpuIdBySpu($v->spu);

                $v->img = '';
                $imgres = Db::table('self_spu_color')->where('base_spu_id', $base_spu_id)->where('color_id',$v->color_id)->first();
               
                if($imgres){
                    $v->img = $imgres->img;
                }

                if($v->conversion_rate>0){
                    $v->conversion_rate = round($v->conversion_rate*100, 2);
                }

                if($v->return_rate){
                    $v->return_rate = round($v->return_rate*100,2);
                }
                $v->conversion_rate_e = $v->conversion_rate.'%';
                $v->return_rate_e = $v->return_rate.'%';
                $v->total_inventory =  $v->fba_inventory + $v->here_inventory + $v->factory_num;
            
                if($v->old_spu){
                    $v->spu = $v->old_spu;
                }

                $orderquery['spu_id'] = $v->id;
                $v->fisrt_order_time = $this->getOrderFirst($orderquery);

                $total_inventory+= $v->total_inventory;
                $total_order += $v->order_num;
                $total_return += $v->return_num;
                $total_inventory_quanzhou += $v->quanzhou_num;
                $total_inventory_tongan += $v->tongan_num;
                $total_cloud_tongan += $v->cloud_num;
                $total_in_stock_num += $v->in_stock_num;
                $total_transfer_num += $v->transfer_num;
                $total_in_bound_num += $v->in_bound_num;
                $total_tongan_request_num += $v->tongan_request_num;
                $total_quanzhou_request_num += $v->quanzhou_request_num;
                $total_cloud_request_num += $v->cloud_request_num;
                $total_courier_num += $v->courier_num;
                $total_shipping_num += $v->shipping_num;
                $total_air_num += $v->air_num;
    
                $total_shipment_order_num += $v->shipment_order_num;
                $total_out_order_num += $v->out_order_num;
                $total_tongan_deduct_inventory+= $v->tongan_deduct_inventory;
                $total_quanzhou_deduct_inventory += $v->quanzhou_deduct_inventory;
                $total_cloud_deduct_inventory+= $v->cloud_deduct_inventory;
               
        }

       //会话率查询
       $sessions_total = [];
       $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('custom_sku_id',$cus_ids)->where('sessions_total','>',0)->groupby('custom_sku_id')->select('custom_sku_id',db::raw('sum(sessions_total) as sessions_total'))->get();

       foreach ($sessions_res as $srv) {
           # code...
           $sessions_total[$srv->custom_sku_id] = $srv->sessions_total;
       }


       $cusids = [];
       foreach ($list as $v) {
           $s_total = 0;

           $cusids = explode(',',$v->cus_ids);
           foreach ($cusids as $cid) {
            # code...
                if(isset($sessions_total[$cid])){
                    $s_total+=$sessions_total[$cid];
                }
           }

           $v->sessions_total = $s_total;
           if($s_total>0&&$v->order_num>0){
            $v->conversion_rate = round(($v->order_num/$s_total)*100,2);
            $v->conversion_rate_e = $v->conversion_rate.'%';
            }

            $v->s = $sessions_total;

        # code...
       }


        $total_no_shipment_num = $total_shipment_order_num-$total_out_order_num;
        $totals['total_inventory'] =  $total_inventory;
        $totals['order_num'] =  $total_order;
        $totals['return_num'] =  $total_return;
        $totals['quanzhou_num'] =  $total_inventory_quanzhou;
        $totals['tongan_num'] =  $total_inventory_tongan;
        $totals['cloud_num'] =  $total_cloud_tongan;
        $totals['in_stock_num'] =  $total_in_stock_num;
        $totals['transfer_num'] =  $total_transfer_num;
        $totals['in_bound_num'] =  $total_in_bound_num;
        $totals['tongan_request_num'] =  $total_tongan_request_num;
        $totals['quanzhou_request_num'] =  $total_quanzhou_request_num;
        $totals['cloud_request_num'] =  $total_cloud_request_num;
        $totals['courier_num'] =  $total_courier_num;
        $totals['shipping_num'] =  $total_shipping_num;
        $totals['air_num'] =  $total_air_num;
        $totals['shipment_order_num'] =  $total_shipment_order_num;
        $totals['out_order_num'] =  $total_out_order_num;
        $totals['tongan_deduct_inventory'] =  $total_tongan_deduct_inventory;
        $totals['quanzhou_deduct_inventory'] =  $total_quanzhou_deduct_inventory;
        $totals['cloud_deduct_inventory'] =  $total_cloud_deduct_inventory;
        $totals['no_shipment_num'] =  $total_no_shipment_num;


        $list = json_decode(json_encode($list),true);

        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }

        if($posttype==2){
            $p['title']='spu颜色数据报表'.time();
            $p['title_list'] = [
                'spu'=>'spu',
                'color' => '颜色',
                'img' => '图片',
                'day_quantity_ordered'=>'日销',
                'order_num'=>'销量',
                'conversion_rate_e'=>'转化率',
                'return_rate_e'=>'退货率',
                'return_num'=>'退货数量',
                'tongan_num'=>'同安仓库存',
                'quanzhou_num'=>'泉州仓库存',
                'cloud_num'=>'云仓库存',
                'factory_num'=>'工厂虚拟仓库存',
                'total_inventory'=>'总库存',
                'in_stock_num'=>'fba在仓',
                'transfer_num'=>'fba预留',
                'in_bound_num'=>'fba在途',
                'here_inventory_day'=>'本地仓周转天数',
                'fba_inventory_day'=>'fba仓周转天数',
                'fba_inventory_day'=>'fba仓周转天数',
                'fisrt_order_time'=>'首单时间',
            ];

            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = 'spu颜色数据报表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }

        $returnlist = [];
        foreach ($list as $k => $v) {
            # code...
            for ($i=$limit * ($page-1); $i < $limit * $page; $i++) { 
                # code...
                if($k==$i){
                    $returnlist[] = $v;
                }
            }

        }


        return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum,'total'=> $totals,'last_update_time'=> $new_update_time];
    }



    public function DatawholeCusNew($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }


        $type =  isset($params['types']) ? $params['types'] : 1;
        switch ($type) {
            case 1:
                # code...
                //当日
                $table = 'cache_cus_today';
                $start_time = date('Y-m-d 00:00:00',time());
                $end_time = date('Y-m-d 23:59:59',time());
                break;
            case 2:
                # code...
                //昨日
                $table = 'cache_cus_yestoday';
                $start_time = date('Y-m-d 00:00:00',time()-86400);
                $end_time = date('Y-m-d 23:59:59',time()-86400);
                break;
            case 3:
                # code...
                //七天
                $table = 'cache_cus_week';
                $start_time = date('Y-m-d 00:00:00',time()-(86400*7));
                $end_time = date('Y-m-d 23:59:59',time());
                break;
            case 4:
                # code...
               //十四天
               $table = 'cache_cus_tweek';
               $start_time = date('Y-m-d 00:00:00',time()-(86400*14));
               $end_time = date('Y-m-d 23:59:59',time());
               break;
            case 5:
                # code...
               //一月
               $table = 'cache_cus_moon';
               $start_time = date('Y-m-d 00:00:00',time()-(86400*30));
               $end_time = date('Y-m-d 23:59:59',time());
               break;
            default:
                # code...
                break;
        }
        
        //初始化查询
        $thisDb = Db::table($table.' as a')->leftjoin('self_custom_sku as b','b.id','=','a.custom_sku_id')->leftjoin('self_spu as c','c.id','=','b.spu_id');
        if (isset($params['custom_sku'])) {
            $thisDb = $thisDb->where('b.custom_sku','like','%'.$params['custom_sku'].'%')->orWhere('b.old_custom_sku','like','%'.$params['custom_sku'].'%');
        }
        if (isset($params['spu_id'])) {
            $thisDb = $thisDb->where('b.spu_id',$params['spu_id']);
        }
        if (isset($params['color'])) {
            $thisDb = $thisDb->where('b.color',$params['color']);
        }
        if (isset($params['spu'])) {
            $thisDb = $thisDb->where('c.spu','like','%'.$params['spu'].'%')->orWhere('c.old_spu','like','%'.$params['spu'].'%');
        }
        $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';

        $totalNum=$thisDb->count();
        $list = $thisDb
            ->offset($pagenNum)
            ->limit($limit)
//            ->select()
            ->orderby('a.'.$orderby,$orderbytype)
            ->get(['b.custom_sku','b.old_custom_sku', 'b.tongan_inventory', 'b.quanzhou_inventory','a.*']);


        $today = date('Y-m-d',time());
        $todaycache = Db::table('cache_cus_today')->where('ds','like',$today.'%')->first();
        if($todaycache){
            $new_update_time  = $todaycache->update_time;
        }
        
        $cus_ids = [];
        foreach ($list as $v) {
            # code...

            if($v->custom_sku_id){
                $cus_ids[] = $v->custom_sku_id;

                // if(!isset($new_update_time)){
                //     $new_update_time = $v->update_time;
                // }
                //预减后库存
//                var_dump($v);exit;
                $tonganLock = $this->GetLocationCustomSkuLockNum($v->custom_sku_id, 0, 1);
                $quanzhouLock = $this->GetLocationCustomSkuLockNum($v->custom_sku_id, 0, 2);
                $tonganLock = array_sum(array_column($tonganLock, 'lock_num'));
                $quanzhouLock = array_sum(array_column($quanzhouLock, 'lock_num'));
                $v->tongan_deduct_inventory = $v->tongan_inventory - $tonganLock;
                $v->quanzhou_deduct_inventory = $v->quanzhou_inventory - $quanzhouLock;
                $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;

            
                //补货提醒 - 本地
                //1 需要下单  2 偏多  3 冗余
                $buhuo_status_bd = 0;
                
                $bdzz = $v->here_inventory_day;
                if ($bdzz >= 0 && $bdzz < 60) {
                    $buhuo_status_bd = 1;
                }
                if ($bdzz >= 60 && $bdzz < 90) {
                    $buhuo_status_bd = 2;
                }
                if ($bdzz > 90) {
                    $buhuo_status_bd = 3;
                }

                $fbazz =  $v->fba_inventory_day;

                $buhuo_status_fba = 0; 
                //补货提醒更新
                if ($fbazz >= 0 && $fbazz < 60) {
                    $buhuo_status_fba = 1;
                }
                if ($fbazz >= 60 && $fbazz < 90) {
                    $buhuo_status_fba = 2;
                }
                if ($fbazz > 90) {
                    $buhuo_status_fba = 3;
                }

                $v->buhuo_status_bd = $buhuo_status_bd; 
                $v->buhuo_status_fba = $buhuo_status_fba; 

                //补货状态  1补货过多 近两周日销*60<计划补货数量
                
                // s_day_quantity_ordered
                $v->send_status = 0;

                $courier_num  = 0;
                $shipping_num = 0;
                $air_num = 0;

                if(isset($v->courier_num)){
                    $courier_num = (int)$v->courier_num;
                }

                if(isset($v->shipping_num)){
                    $shipping_num = (int)$v->shipping_num;
                }
                if(isset($v->air_num)){
                    $air_num = (int)$v->air_num;
                }

                $jh_buhuo = $courier_num+$shipping_num+$air_num;
                //计划发货
                if($jh_buhuo>$v->day_quantity_ordered*60){
                    $v->send_status = 1;
                }


                //下单状态  1下单过多 近两周日销*45<未出货数量
                $v->place_order_status = 0;
                
                if($v->no_shipment_num>$v->day_quantity_ordered*45){
                    $v->place_order_status = 1;
                }
                // //出入库时间
                // //出
                // //同安
                // if(isset($params['shop_id'])){
                //     $shop_id = $params['shop_id'];
                // }

                // $outdata1 = db::table('saihe_warehouse_log')->where('custom_sku_id',$v->custom_sku_id)->whereIn('warehouse_id',[2,386])->where('type',1);
                // if(isset($params['shop_id'])){
                //     $outdata1 =  $outdata1->where('shop_id',$shop_id);
                // }
                // $outdata1 =  $outdata1->orderBy('operation_date','DESC')->select('operation_date')->first();

                // //泉州
                // $outdata2 = db::table('saihe_warehouse_log')->where('custom_sku_id',$v->custom_sku_id)->where('warehouse_id',560)->where('type',1);
                // if(isset($params['shop_id'])){
                //     $outdata2 =  $outdata2->where('shop_id',$shop_id);
                // }
                // $outdata2 =  $outdata2->orderBy('operation_date','DESC')->select('operation_date')->first();

                // //万翔
                // $outdata3 = db::table('cloudhouse_record')->where('custom_sku_id',$v->custom_sku_id)->where('type',1)->orderBy('createtime','DESC')->select('createtime')->first();

                // //入
                // //同安
                // $indata1 = db::table('saihe_warehouse_log')->where('custom_sku_id',$v->custom_sku_id)->whereIn('warehouse_id',[2,386])->where('type',2);
                // if(isset($params['shop_id'])){
                //     $indata1 =  $indata1->where('shop_id',$shop_id);
                // }
                // $indata1 =  $indata1->orderBy('operation_date','DESC')->select('operation_date')->first();

                // //泉州
                // $indata2 = db::table('saihe_warehouse_log')->where('custom_sku_id',$v->custom_sku_id)->where('warehouse_id',560)->where('type',2);
                // if(isset($params['shop_id'])){
                //     $indata2 =  $indata2->where('shop_id',$shop_id);
                // }
                // $indata2 =  $indata2->orderBy('operation_date','DESC')->select('operation_date')->first();


                // //万翔

                // $indata3 = db::table('cloudhouse_record')->where('custom_sku_id',$v->custom_sku_id)->where('type',2)->orderBy('createtime','DESC')->select('createtime')->first();

                // $v->out1 = '';
                // $v->out2 = '';
                // $v->out3 = '';
                // $v->in1 = '';
                // $v->in2 = '';
                // $v->in3 = '';
                // if($outdata1){
                //     $v->out1 = date('Y-m-d', strtotime($outdata1->operation_date));
                // }
                // if($outdata2){
                //     $v->out1 = date('Y-m-d', strtotime($outdata2->operation_date));
                // }
                // if($outdata3){
                //     $v->out1 = date('Y-m-d', strtotime($outdata3->createtime));
                // }
                // if($indata1){
                //     $v->out1 = date('Y-m-d', strtotime($indata1->operation_date));
                // }
                // if($indata2){
                //     $v->out1 = date('Y-m-d', strtotime($indata2->operation_date));
                // }
                // if($indata3){
                //     $v->out1 = date('Y-m-d', strtotime($indata3->createtime));
                // }
                $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
                //fba仓库存
                $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
                //本地仓库存
    
                if($v->old_custom_sku){
                    $v->custom_sku = $v->old_custom_sku;
                }

                $v->img = $this->GetCustomskuImg($v->custom_sku);
                if($v->conversion_rate>0){
                    $v->conversion_rate = round($v->conversion_rate, 2)*100;
                }

                if($v->return_rate){
                    $v->return_rate = round($v->return_rate ,2)*100;
                }
              
                $v->conversion_rate_e = $v->conversion_rate.'%';
                $v->return_rate_e = $v->return_rate.'%';
                
                $orderquery['custom_sku_id'] = $v->custom_sku_id;
                $v->fisrt_order_time = $this->getOrderFirst($orderquery);

                $v->total_inventory =  $v->fba_inventory + $v->here_inventory + $v->factory_num;
                
            }
        }

        //会话率查询
       $sessions_total = [];
       $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('custom_sku_id',$cus_ids)->where('sessions_total','>',0)->groupby('custom_sku_id')->select('custom_sku_id',db::raw('sum(sessions_total) as sessions_total'))->get();

       foreach ($sessions_res as $srv) {
           # code...
           $sessions_total[$srv->custom_sku_id] = $srv->sessions_total;
       }

       foreach ($list as $v) {
        $s_total = 0;
        if(isset($sessions_total[$v->custom_sku_id])){
            $s_total =$sessions_total[$v->custom_sku_id];
        }
        

        $v->sessions_total = $s_total;
        if($s_total>0&&$v->order_num>0){
         $v->conversion_rate = round(($v->order_num/$s_total)*100,2);
         $v->conversion_rate_e = $v->conversion_rate.'%';
         }

         $v->s = $sessions_total;

     # code...
    }



        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }

        if($posttype==2){
            $p['title']='库存sku数据报表'.time();
            $p['title_list'] = [
                'custom_sku'=>'库存sku',
                'img' => '图片',
                'day_quantity_ordered'=>'日销',
                'order_num'=>'销量',
                'conversion_rate_e'=>'转化率',
                'return_rate_e'=>'退货率',
                'return_num'=>'退货数量',
                'tongan_num'=>'同安仓库存',
                'quanzhou_num'=>'泉州仓库存',
                'deposit_num'=>'工厂寄存仓',
                'cloud_num'=>'云仓库存',
                'factory_num'=>'工厂虚拟仓库存',
                'total_inventory'=>'总库存',
                'in_stock_num'=>'fba在仓',
                'transfer_num'=>'fba预留',
                'in_bound_num'=>'fba在途',
                'here_inventory_day'=>'本地仓周转天数',
                'fba_inventory_day'=>'fba仓周转天数',
                'fba_inventory_day'=>'fba仓周转天数',
                'fisrt_order_time'=>'首单时间',
            ];

            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = '库存sku数据报表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
        }


        return ['type'=>'success','data' => $list,'totalnum' => $totalNum,'last_update_time'=>$new_update_time];
    }



    // //提前缓存
    // public function DatawholeCachespu($params){
    //     $start_time = $params['start_time'];
    //     $end_time = $params['end_time'];
    //     $caches = Redis::Del('datacache-new:cache_spu:'.$start_time.$end_time);
    //     $caches = Db::table('cache_spu')->whereBetween('ds', [$start_time, $end_time])->get();
    //     $spu_cache = [];
    //     foreach ($caches as $v) {
    //         # code...
    //         if(isset($spu_cache[$v->spu_id]['order_num'])){
    //             $spu_cache[$v->spu_id]['order_num'] +=$v->order_num;
    //         }else{
    //             $spu_cache[$v->spu_id]['order_num'] = 0;
    //         }
    //         if(isset($spu_cache[$v->spu_id]['session_percentage'])){
    //             $spu_cache[$v->spu_id]['session_percentage'] +=$v->session_percentage;
    //         }else{
    //             $spu_cache[$v->spu_id]['session_percentage'] = 0;
    //         }
    //         if(isset($spu_cache[$v->spu_id]['return_num'])){
    //             $spu_cache[$v->spu_id]['return_num'] +=$v->return_num;
    //         }else{
    //             $spu_cache[$v->spu_id]['return_num'] = 0;
    //         }
    //         $spu_cache[$v->spu_id]['spu_id'] = $v->spu_id;
    //     }

    //     $spu_cache = array_values($spu_cache);


    //     Redis::Set('datacache-new:cache_spu:'.$start_time.$end_time,json_encode($spu_cache));
    //     return true;
    // }

    public function getOrderFirst($params){
        $time = '';
        if(isset($params['spu_id'])){
            $res = Redis::Hget('datacache:order_first_spu',$params['spu_id']);
            if($res){
                $time = $res;
            }else{
                $res = Db::table('amazon_order_item')->where('spu_id',$params)->orderby('amazon_time','ASC')->first();
                if($res){
                    $time = $res->amazon_time;
                    $res = Redis::Hset('datacache:order_first_spu',$params['spu_id'],$time);
                }else{
                    $time = '';
                }
            }
        }
        if(isset($params['custom_sku_id'])){
            $res = Redis::Hget('datacache:order_first_cus',$params['custom_sku_id']);
            if($res){
                $time = $res;
            }else{
                $res = Db::table('amazon_order_item')->where('custom_sku_id',$params)->orderby('amazon_time','ASC')->first();
                if($res){
                    $time = $res->amazon_time;
                    $res = Redis::Hset('datacache:order_first_cus',$params['custom_sku_id'],$time);
                }else{
                    $time = '';
                }
            }
        }
        if(isset($params['sku_id'])){
            $res = Redis::Hget('datacache:order_first_sku',$params['sku_id']);
            if($res){
                $time = $res;
            }else{
                $res = Db::table('amazon_order_item')->where('sku_id',$params)->orderby('amazon_time','ASC')->first();
                if($res){
                    $time = $res->amazon_time;
                    $res = Redis::Hset('datacache:order_first_sku',$params['sku_id'],$time);
                }else{
                    $time = '';
                }
            }
        }
       
        return $time;
    }

    public function DatawholeShopSpuColor($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        
        //初始化查询
        $thisDb = Db::table('self_sku as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->leftjoin('self_spu as c','a.spu_id','=','c.id')->leftjoin('self_base_spu as d','c.base_spu_id','=','d.id');

        if (isset($params['spu'])) {
            // $thisDb = $thisDb->where('c.spu','like','%'.$params['spu'].'%')->orWhere('c.old_spu','like','%'.$params['spu'].'%');
            $thisDb = $thisDb->where('c.spu',$params['spu'])->orWhere('c.old_spu',$params['spu']);
        }
        if (isset($params['spu_id'])) {
            $thisDb = $thisDb->where('c.id',$params['spu_id']);
        }else{
            return ['type'=>'fail','msg'=>'无spu_id'];
        }

        if (isset($params['start_time'])) {
            $start = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end = $params['end_time'];
        }

        $shop_id =  $params['shop_id']??34;
        $thisDb = $thisDb->where('a.shop_id',$shop_id);


        $start_time = isset($start) ? $start : date('Y-m-d', time());
        $end_time = isset($end) ? $end : date('Y-m-d', time());

        $end_time = $end_time.' 23:59:59';
        $today = date('Y-m-d',time());



  
        $listres = $thisDb
        ->select('b.id as custom_sku_id','b.color','b.color_id','c.spu','c.old_spu','c.id','d.one_cate_id','d.three_cate_id','d.user_id')
        ->get();

        $cus_ids =  [];
        $list = [];
        foreach ($listres as $v) {
            # code...
            $cus_ids[] = $v->custom_sku_id;
            $list[$v->color]['spu'] = $v->spu;
            $list[$v->color]['color'] = $v->color;
            if($v->old_spu){
                $list[$v->color]['spu'] = $v->old_spu;
            }
            $list[$v->color]['custom_sku_ids'][] = $v->custom_sku_id;
            $list[$v->color]['color_id'] = $v->color_id;
            $list[$v->color]['spu_id'] = $v->id;
            $list[$v->color]['one_cate_id'] = $v->one_cate_id;
            $list[$v->color]['three_cate_id'] = $v->three_cate_id;
            $list[$v->color]['user_id'] = $v->user_id;
            // $list[$v->color] = $v;
        }

        $totalNum = count($list);


        //会话率查询
       $sessions_total = [];
       $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('custom_sku_id',$cus_ids)->where('sessions_total','>',0)->groupby('custom_sku_id')->select('custom_sku_id',db::raw('sum(sessions_total) as sessions_total'))->get();

       foreach ($sessions_res as $srv) {
           # code...
           $sessions_total[$srv->custom_sku_id] = $srv->sessions_total;
       }

        //无店铺 本地（quanzhou_num，tongan_num，cloud_num，factory_num） 下单（shipment_order_num）  生产 （shipment_order_num） 
        //有店铺 会话率（session_percentage） 退货（return_num） 订单（order_num） fba(in_stock_num,transfer_num,in_bound_num)  计划发货（tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）

 
        
        $query['type'] = 'custom_sku_id';
        $query['shop_id'] = $shop_id;
        $query['start'] =  $start_time;
        $query['end'] = $end_time;

        $return_res = $this->getReturnByShop($query);
        $order_res = $this->getOrdeByShop($query);
        $fba_res = $this->getFbaByShop($query);
        $sales_res = $this->getSalesByShop($query);
        $request_res = $this->getRequestByShop($query);

        
        $cache_res = Db::table('cache_cus_today')->where('ds','like', "{$today}%")->get();
        $other_res =[];
        foreach ($cache_res as $v) {
            # code...
            $other_res[$v->custom_sku_id]['quanzhou_num']  = $v->quanzhou_num;
            $other_res[$v->custom_sku_id]['tongan_num']  = $v->tongan_num;
            $other_res[$v->custom_sku_id]['deposit_num']  = $v->deposit_num;
            
            $other_res[$v->custom_sku_id]['cloud_num']  = $v->cloud_num;
            $other_res[$v->custom_sku_id]['factory_num']  = $v->factory_num;
            $other_res[$v->custom_sku_id]['out_order_num']  = $v->out_order_num;
            $other_res[$v->custom_sku_id]['shipment_order_num']  = $v->shipment_order_num;
        }


        $list = json_decode(json_encode($list),false);


        foreach ($list as $v) {
            $custom_sku_ids = $v->custom_sku_ids;

              //本地仓
              $v->quanzhou_num = 0;
              $v->tongan_num = 0;
              $v->cloud_num = 0;
              $v->deposit_num = 0;
              $v->factory_num = 0;
              //生产下单
              $v->out_order_num = 0;
              $v->shipment_order_num = 0;
  
              //会话率 sales_res sales_num
              $v->sales_num = 0;
  
              //退货 return_res return_num
              $v->return_num = 0;
  
              //订单 order_res order_num
              $v->order_num = 0;
  
              //fba fba_res (in_stock_num,transfer_num,in_bound_num)
              $v->in_stock_num = 0;
              $v->transfer_num = 0;
              $v->in_bound_num = 0;
              //计划发货 request_res （tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）
              $v->tongan_request_num = 0;
              $v->quanzhou_request_num = 0;
              $v->cloud_request_num = 0;
              $v->courier_num = 0;
              $v->shipping_num = 0;
              $v->air_num = 0;

              $orderss = [];

            foreach ($custom_sku_ids as $custom_sku_id) {
                # code...
                  //本地仓
                $quanzhou_num = $other_res[$custom_sku_id]['quanzhou_num']??0;
                $deposit_num = $other_res[$custom_sku_id]['deposit_num']??0;
                
                $v->quanzhou_num  +=$quanzhou_num;
                $v->deposit_num +=$deposit_num;
                
                $tongan_num = $other_res[$custom_sku_id]['tongan_num']??0;
                
                $v->tongan_num  +=$tongan_num;
                
               

                $cloud_num = $other_res[$custom_sku_id]['cloud_num']??0;
                
                $v->cloud_num  +=$cloud_num;
                

                $factory_num = $other_res[$custom_sku_id]['factory_num']??0;
                
                $v->factory_num +=$factory_num;
                
                //生产下单
                $out_order_num = $other_res[$custom_sku_id]['out_order_num']??0;
                
                $v->out_order_num +=$out_order_num;
                

                $shipment_order_num = $other_res[$custom_sku_id]['shipment_order_num']??0;
                
                $v->shipment_order_num  +=$shipment_order_num;
                

                //会话率 sales_res sales_num
                $sales_num = $sales_res[$custom_sku_id]??0;
                
                $v->sales_num  +=$sales_num;
                

                //退货 return_res return_num
                $return_num = $return_res[$custom_sku_id]??0;
                
                $v->return_num  +=$return_num;
                

                //订单 order_res order_num
                $order_num = $order_res[$custom_sku_id]??0;
                
                $v->order_num  +=$order_num;
                
                $orderss[$custom_sku_id] = $order_num;
                //fba fba_res (in_stock_num,transfer_num,in_bound_num)
                $in_stock_num = $fba_res[$custom_sku_id]['in_stock_num']??0;
                
                $v->in_stock_num  +=$in_stock_num;
                
                $transfer_num = $fba_res[$custom_sku_id]['transfer_num']??0;
                
                $v->transfer_num  +=$transfer_num;
                
                $in_bound_num = $fba_res[$custom_sku_id]['in_bound_num']??0;
               
                $v->in_bound_num  +=$in_bound_num;
                
                //计划发货 request_res （tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）
                $tongan_request_num = $request_res[$custom_sku_id]['tongan_request_num']??0;
                
                $v->tongan_request_num  +=$tongan_request_num;
                
                $quanzhou_request_num = $request_res[$custom_sku_id]['quanzhou_request_num']??0;
                
                $v->quanzhou_request_num  +=$quanzhou_request_num;
                
                $cloud_request_num = $request_res[$custom_sku_id]['cloud_request_num']??0;
                
                $v->cloud_request_num  +=$cloud_request_num;
                
                $courier_num = $request_res[$custom_sku_id]['courier_num']??0;
                
                $v->courier_num  +=$courier_num;
                
                $shipping_num = $request_res[$custom_sku_id]['shipping_num']??0;

                $v->shipping_num  +=$shipping_num;
                
                $air_num = $request_res[$custom_sku_id]['air_num']??0;
 
                $v->air_num  +=$air_num;
                
            }
          
            $v->orderss = $orderss;

            //预减后库存
            $v->tongan_deduct_inventory = $v->tongan_num - $v->tongan_request_num;
            $v->quanzhou_deduct_inventory = $v->quanzhou_num - $v->quanzhou_request_num;
            $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;
   
            //未出货
            $v->no_shipment_num = $v->shipment_order_num-$v->out_order_num;
            if($v->no_shipment_num<0){
                $v->no_shipment_num  = 0;
            }
            //转化率
            $v->conversion_rate = 0;
            //退货率
            $v->return_rate = 0;
            if($v->order_num>0){
                if( $v->sales_num>0){
                    $v->conversion_rate = round($v->order_num/$v->sales_num, 4) * 100;
                }

                if($v->return_num>0){
                    $v->return_rate = round($v->return_num/$v->order_num ,4) * 100;
                }

            }
   
            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400);
            $day_quantity_ordered = 0;
            if ($v->order_num > 0) {
                $day_quantity_ordered = round($v->order_num / $day, 2);
            }
            $v->day_quantity_ordered = $day_quantity_ordered;
   
   
            $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
            //fba仓库存
            $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
            //本地仓库存

            $v->here_inventory_day = 999;
            //本地仓库存周转天数
            $v->fba_inventory_day = 999;
            //fba仓库存周转天数
            if ($day_quantity_ordered == 0) {
                $v->here_inventory_day = 999;
                $v->fba_inventory_day = 999;
            }

            if ($v->here_inventory == 0) {
                $v->here_inventory_day = 0;
            }
            if ($v->fba_inventory == 0) {
                $v->fba_inventory_day = 0;
            }

            if ($day_quantity_ordered > 0 && $v->here_inventory > 0) {
                //本地仓库存周转天数=同安库存/日销
                $v->here_inventory_day = round($v->here_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $v->fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $v->fba_inventory_day = round($v->fba_inventory / $day_quantity_ordered, 2);
            }

            
            //补货提醒 - 本地
            //1 需要下单  2 偏多  3 冗余
            $buhuo_status_bd = 0;
            
            $bdzz = $v->here_inventory_day;
            if ($bdzz >= 0 && $bdzz < 60) {
                $buhuo_status_bd = 1;
            }
            if ($bdzz >= 60 && $bdzz < 90) {
                $buhuo_status_bd = 2;
            }
            if ($bdzz > 90) {
                $buhuo_status_bd = 3;
            }

            $fbazz =  $v->fba_inventory_day;
            //补货提醒-fba
            // $inventory_turnover = $this->inventoryTurnoverStatus($fba_inventory, $day_quantity_ordered, $plan_multiple);

            $buhuo_status_fba = 0; 
            //补货提醒更新
            if ($fbazz >= 0 && $fbazz < 60) {
                $buhuo_status_fba = 1;
            }
            if ($fbazz >= 60 && $fbazz < 90) {
                $buhuo_status_fba = 2;
            }
            if ($fbazz > 90) {
                $buhuo_status_fba = 3;
            }

            $v->buhuo_status_bd = $buhuo_status_bd; 
            $v->buhuo_status_fba = $buhuo_status_fba; 

            //补货状态  1补货过多 近两周日销*60<计划补货数量
            
            // s_day_quantity_ordered
            $v->send_status = 0;

            $courier_num  = 0;
            $shipping_num = 0;
            $air_num = 0;

            if(isset($v->courier_num)){
                $courier_num = (int)$v->courier_num;
            }

            if(isset($v->shipping_num)){
                $shipping_num = (int)$v->shipping_num;
            }
            if(isset($v->air_num)){
                $air_num = (int)$v->air_num;
            }

            $jh_buhuo = $courier_num+$shipping_num+$air_num;
            //计划发货
            if($jh_buhuo>$day_quantity_ordered*60){
                $v->send_status = 1;
            }


            //下单状态  1下单过多 近两周日销*45<未出货数量
            $v->place_order_status = 0;
            
            if($v->no_shipment_num>$day_quantity_ordered*45){
                $v->place_order_status = 1;
            }


   
            # code...
        }




        $list = json_decode(json_encode($list),true);
        


        $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';


        // $sort = $params['sort']??'order_num';
        $sort_list = array_column($list, $orderby);

        if($orderbytype=='DESC'){
            array_multisort($sort_list, SORT_DESC, $list);
        }else{
            array_multisort($sort_list, SORT_ASC, $list);
        }


        $returnlist = [];
        foreach ($list as $k => $v) {
            # code...
            for ($i=$limit * ($page-1); $i < $limit * $page; $i++) { 
                # code...
                if($k==$i){
                    $returnlist[] = $v;
                }
            }

        }


        $cusids = [];
        foreach ($returnlist as &$v){

            $s_total = 0;
            foreach ($v['custom_sku_ids'] as $cid) {
                # code...
                if(isset($sessions_total[$cid])){
                    $s_total+=$sessions_total[$cid];
                }
            }

            
            $v['sessions_total'] = $s_total;
            if($s_total>0&&$v['order_num']>0){
            $v['conversion_rate'] = round(($v['order_num']/$s_total)*100,2);
            $v['conversion_rate_e'] = $v['conversion_rate'].'%';
            }

            $v['s'] = $sessions_total;
    

            $base_spu_id = $this->GetBaseSpuIdBySpu($v['spu']);

            $v['img'] = '';
            $imgres = Db::table('self_spu_color')->where('base_spu_id', $base_spu_id)->where('color_id',$v['color_id'])->first();
           
            if($imgres){
                $v['img'] = $imgres->img;
            }

            if(isset($v['old_custom_sku'])){
                $v['custom_sku'] = $v['old_custom_sku'];
            }
            // $v['conversion_rate'] = round($v['conversion_rate'] ,2);
            $v['return_rate'] = round($v['return_rate'] ,2);
            $v['user'] = $this->GetUsers($v['user_id'])['account'];

            $orderquery['spu_id'] = $v['spu_id'];
            $v['fisrt_order_time'] = $this->getOrderFirst($orderquery);
        }


        return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum];
        // return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum,'total'=> $totals];
 
        //获取累加数据

    }

    public function DatawholeShopCus($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        
        //初始化查询
        $thisDb = Db::table('self_sku as a')->leftjoin('self_custom_sku as b','a.custom_sku_id','=','b.id')->leftjoin('self_spu as c','a.spu_id','=','c.id')->leftjoin('self_base_spu as d','c.base_spu_id','=','d.id');

        if (isset($params['spu'])) {
            $thisDb = $thisDb->where('c.spu','like','%'.$params['spu'].'%')->orWhere('c.old_spu','like','%'.$params['spu'].'%');
        }
        if (isset($params['spu_id'])) {
            $thisDb = $thisDb->where('c.id',$params['spu_id']);
        }

        if (isset($params['start_time'])) {
            $start = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end = $params['end_time'];
        }

        if (isset($params['color'])) {
            $thisDb = $thisDb->where('b.color',$params['color']);
        }

        $shop_id =  $params['shop_id']??34;
        $thisDb = $thisDb->where('a.shop_id',$shop_id);


        $start_time = isset($start) ? $start : date('Y-m-d', time());
        $end_time = isset($end) ? $end : date('Y-m-d', time());

        $end_time = $end_time.' 23:59:59';
        $today = date('Y-m-d',time());



        $totalNum=$thisDb->groupby('a.custom_sku_id')->get()->count();

  
        $list = $thisDb
        ->select('a.id as sku_id','b.id','b.custom_sku','b.old_custom_sku','d.one_cate_id','d.three_cate_id','d.user_id')
        ->groupby('a.custom_sku_id')
        ->get();

        //无店铺 本地（quanzhou_num，tongan_num，cloud_num，factory_num） 下单（shipment_order_num）  生产 （shipment_order_num） 
        //有店铺 会话率（session_percentage） 退货（return_num） 订单（order_num） fba(in_stock_num,transfer_num,in_bound_num)  计划发货（tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）

        
        $query['type'] = 'custom_sku_id';
        $query['shop_id'] = $shop_id;
        $query['start'] =  $start_time;
        $query['end'] = $end_time;

        $return_res = $this->getReturnByShop($query);
        $order_res = $this->getOrdeByShop($query);
        $fba_res = $this->getFbaByShop($query);
        $sales_res = $this->getSalesByShop($query);
        $request_res = $this->getRequestByShop($query);

        
        $cache_res = Db::table('cache_cus_today')->where('ds','like', "{$today}%")->get();
        $other_res =[];
        foreach ($cache_res as $v) {
            # code...
            $other_res[$v->custom_sku_id]['quanzhou_num']  = $v->quanzhou_num;
            $other_res[$v->custom_sku_id]['tongan_num']  = $v->tongan_num;
            $other_res[$v->custom_sku_id]['cloud_num']  = $v->cloud_num;
            $other_res[$v->custom_sku_id]['factory_num']  = $v->factory_num;
            $other_res[$v->custom_sku_id]['out_order_num']  = $v->out_order_num;
            $other_res[$v->custom_sku_id]['shipment_order_num']  = $v->shipment_order_num;
        }


        foreach ($list as $v) {
            $custom_sku_id = $v->id;
            //本地仓
            $v->quanzhou_num = $other_res[$custom_sku_id]['quanzhou_num']??0;
            $v->tongan_num = $other_res[$custom_sku_id]['tongan_num']??0;
            $v->cloud_num = $other_res[$custom_sku_id]['cloud_num']??0;
            $v->factory_num = $other_res[$custom_sku_id]['factory_num']??0;
            //生产下单
            $v->out_order_num = $other_res[$custom_sku_id]['out_order_num']??0;
            $v->shipment_order_num = $other_res[$custom_sku_id]['shipment_order_num']??0;

            //会话率 sales_res sales_num
            $v->sales_num = $sales_res[$custom_sku_id]??0;

            //退货 return_res return_num
            $v->return_num = $return_res[$custom_sku_id]??0;

            //订单 order_res order_num
            $v->order_num = $order_res[$custom_sku_id]??0;

            //fba fba_res (in_stock_num,transfer_num,in_bound_num)
            $v->in_stock_num = $fba_res[$custom_sku_id]['in_stock_num']??0;
            $v->transfer_num = $fba_res[$custom_sku_id]['transfer_num']??0;
            $v->in_bound_num = $fba_res[$custom_sku_id]['in_bound_num']??0;
            //计划发货 request_res （tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）
            $v->tongan_request_num = $request_res[$custom_sku_id]['tongan_request_num']??0;
            $v->quanzhou_request_num = $request_res[$custom_sku_id]['quanzhou_request_num']??0;
            $v->cloud_request_num = $request_res[$custom_sku_id]['cloud_request_num']??0;
            $v->courier_num = $request_res[$custom_sku_id]['courier_num']??0;
            $v->shipping_num = $request_res[$custom_sku_id]['shipping_num']??0;
            $v->air_num = $request_res[$custom_sku_id]['air_num']??0;

            //预减后库存
            $v->tongan_deduct_inventory = $v->tongan_num - $v->tongan_request_num;
            $v->quanzhou_deduct_inventory = $v->quanzhou_num - $v->quanzhou_request_num;
            $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;
   
            //未出货
            $v->no_shipment_num = $v->shipment_order_num-$v->out_order_num;
            if($v->no_shipment_num<0){
                $v->no_shipment_num  = 0;
            }
            //转化率
            $v->conversion_rate = 0;
            //退货率
            $v->return_rate = 0;
            if($v->order_num>0){
                if( $v->sales_num>0){
                    $v->conversion_rate = round($v->order_num/$v->sales_num, 4) * 100;
                }

                if($v->return_num>0){
                    $v->return_rate = round($v->return_num/$v->order_num ,4) * 100;
                }

            }
   
            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400);
            $day_quantity_ordered = 0;
            if ($v->order_num > 0) {
                $day_quantity_ordered = round($v->order_num / $day, 2);
            }
            $v->day_quantity_ordered = $day_quantity_ordered;
   
   
            $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
            //fba仓库存
            $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
            //本地仓库存

            $v->here_inventory_day = 999;
            //本地仓库存周转天数
            $v->fba_inventory_day = 999;
            //fba仓库存周转天数
            if ($day_quantity_ordered == 0) {
                $v->here_inventory_day = 999;
                $v->fba_inventory_day = 999;
            }

            if ($v->here_inventory == 0) {
                $v->here_inventory_day = 0;
            }
            if ($v->fba_inventory == 0) {
                $v->fba_inventory_day = 0;
            }

            if ($day_quantity_ordered > 0 && $v->here_inventory > 0) {
                //本地仓库存周转天数=同安库存/日销
                $v->here_inventory_day = round($v->here_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $v->fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $v->fba_inventory_day = round($v->fba_inventory / $day_quantity_ordered, 2);
            }

            
            //补货提醒 - 本地
            //1 需要下单  2 偏多  3 冗余
            $buhuo_status_bd = 0;
            
            $bdzz = $v->here_inventory_day;
            if ($bdzz >= 0 && $bdzz < 60) {
                $buhuo_status_bd = 1;
            }
            if ($bdzz >= 60 && $bdzz < 90) {
                $buhuo_status_bd = 2;
            }
            if ($bdzz > 90) {
                $buhuo_status_bd = 3;
            }

            $fbazz =  $v->fba_inventory_day;
            //补货提醒-fba
            // $inventory_turnover = $this->inventoryTurnoverStatus($fba_inventory, $day_quantity_ordered, $plan_multiple);

            $buhuo_status_fba = 0; 
            //补货提醒更新
            if ($fbazz >= 0 && $fbazz < 60) {
                $buhuo_status_fba = 1;
            }
            if ($fbazz >= 60 && $fbazz < 90) {
                $buhuo_status_fba = 2;
            }
            if ($fbazz > 90) {
                $buhuo_status_fba = 3;
            }

            $v->buhuo_status_bd = $buhuo_status_bd; 
            $v->buhuo_status_fba = $buhuo_status_fba; 

            //补货状态  1补货过多 近两周日销*60<计划补货数量
            
            // s_day_quantity_ordered
            $v->send_status = 0;

            $courier_num  = 0;
            $shipping_num = 0;
            $air_num = 0;

            if(isset($v->courier_num)){
                $courier_num = (int)$v->courier_num;
            }

            if(isset($v->shipping_num)){
                $shipping_num = (int)$v->shipping_num;
            }
            if(isset($v->air_num)){
                $air_num = (int)$v->air_num;
            }

            $jh_buhuo = $courier_num+$shipping_num+$air_num;
            //计划发货
            if($jh_buhuo>$day_quantity_ordered*60){
                $v->send_status = 1;
            }


            //下单状态  1下单过多 近两周日销*45<未出货数量
            $v->place_order_status = 0;
            
            if($v->no_shipment_num>$day_quantity_ordered*45){
                $v->place_order_status = 1;
            }


   

            $buhuores = Db::table('cache_buhuo_warning')->where('sku_id',$v->sku_id)->first();

            $v->buhuo_status = 0;
            $v->total_need_inventory = 0;
            if($buhuores){
                $v->buhuo_status = $buhuores->buhuo_satus;
                $v->total_need_inventory = $buhuores->total_need_inventory;
            }

         
            # code...
        }




        $list = json_decode(json_encode($list),true);
        


        $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';


        // $sort = $params['sort']??'order_num';
        $sort_list = array_column($list, $orderby);

        if($orderbytype=='DESC'){
            array_multisort($sort_list, SORT_DESC, $list);
        }else{
            array_multisort($sort_list, SORT_ASC, $list);
        }


        $returnlist = [];
        foreach ($list as $k => $v) {
            # code...
            for ($i=$limit * ($page-1); $i < $limit * $page; $i++) { 
                # code...
                if($k==$i){
                    if(isset($params['buhuo_status'])){
                        $buhuo_status = $params['buhuo_status'];
                        if($v->buhuo_status==$buhuo_status){
                            $returnlist[] = $v;
                        }
                    }else{
                        $returnlist[] = $v;
                    }
                }
            }

        }

        foreach ($returnlist as &$v){
            $v['img'] = $this->GetCustomskuImg($v['custom_sku']);
            if(isset($v['old_custom_sku'])){
                $v['custom_sku'] = $v['old_custom_sku'];
            }
            $v['conversion_rate'] = round($v['conversion_rate'] ,2);
            $v['return_rate'] = round($v['return_rate'] ,2);
            $v['user'] = $this->GetUsers($v['user_id'])['account'];

            $orderquery['custom_sku_id'] = $v['id'];
            $v['fisrt_order_time'] = $this->getOrderFirst($orderquery);
            // $buhuores = Db::table('cache_buhuo_warning')->where('sku_id',$v['sku_id'])->first();
            // $v['buhuo_status'] = 0;
            // $v['total_need_inventory'] = 0;
            // if($buhuores){
            //     $v['buhuo_status'] = $buhuores->buhuo_satus;
            //     $v['total_need_inventory'] = $buhuores->total_need_inventory;
            // }
           
        }


        return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum];
        // return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum,'total'=> $totals];
 
        //获取累加数据

    }
    
    public function DatawholeSpuGetRequestUser($params){
        $spu_id = $params['spu_id'];
        $res = db::table('amazon_buhuo_request as a')->leftjoin('amazon_buhuo_detail as b','a.id','=','b.request_id')->where('b.spu_id',$spu_id)->groupBy('a.request_userid')->select('a.request_userid')->get();
        $list = [];
        foreach ($res as $v) {
            # code...
            $username = $this->GetUsers($v->request_userid)['account'];
            if(!empty($username)){
                $list[] = $username;
            }
            
        }
        return['type'=>'success','data'=>$list];
    }


    public function DatawholeShopSpu($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        
        //初始化查询
        $thisDb = Db::table('self_sku as a')->leftjoin('self_spu as b','a.spu_id','=','b.id')->leftjoin('self_base_spu as c','b.base_spu_id','=','c.id');

        if (isset($params['user_id'])) {
            $thisDb = $thisDb->whereIn('c.user_id',$params['user_id']);
        }
        if (isset($params['spu'])) {
            $thisDb = $thisDb->where('b.spu','like','%'.$params['spu'].'%')->orWhere('b.old_spu','like','%'.$params['spu'].'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->where('c.one_cate_id','=',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->where('c.two_cate_id','=',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->where('c.three_cate_id','=',$params['three_cate_id']);
        }
        if (isset($params['start_time'])) {
            $start = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end = $params['end_time'];
        }

        $shop_id =  $params['shop_id']??34;
        $thisDb = $thisDb->where('a.shop_id',$shop_id);


        $start_time = isset($start) ? $start : date('Y-m-d', time());
        $end_time = isset($end) ? $end : date('Y-m-d', time());

        $end_time = $end_time.' 23:59:59';
        $today = date('Y-m-d',time());



        $totalNum=$thisDb->groupby('a.spu_id')->get()->count();

  
        $list = $thisDb
        ->select('b.id','b.spu','b.old_spu','c.one_cate_id','c.three_cate_id','c.user_id')
        ->groupby('a.spu_id')
        ->get();

        //无店铺 本地（quanzhou_num，tongan_num，cloud_num，factory_num） 下单（shipment_order_num）  生产 （shipment_order_num） 
        //有店铺 会话率（session_percentage） 退货（return_num） 订单（order_num） fba(in_stock_num,transfer_num,in_bound_num)  计划发货（tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）

        
        $query['type'] = 'spu_id';
        $query['shop_id'] = $shop_id;
        $query['start'] =  $start_time;
        $query['end'] = $end_time;

        $return_res = $this->getReturnByShop($query);
        $order_res = $this->getOrdeByShop($query);
        $fba_res = $this->getFbaByShop($query);
        $sales_res = $this->getSalesByShop($query);
        $request_res = $this->getRequestByShop($query);

        
        $cache_res = Db::table('cache_spu')->where('ds','like', "{$today}%")->get();
        $other_res =[];
        foreach ($cache_res as $v) {
            # code...
            $other_res[$v->spu_id]['quanzhou_num']  = $v->quanzhou_num;
            $other_res[$v->spu_id]['tongan_num']  = $v->tongan_num;
            $other_res[$v->spu_id]['deposit_num']  = $v->deposit_num;
            $other_res[$v->spu_id]['cloud_num']  = $v->cloud_num;
            $other_res[$v->spu_id]['factory_num']  = $v->factory_num;
            $other_res[$v->spu_id]['out_order_num']  = $v->out_order_num;
            $other_res[$v->spu_id]['shipment_order_num']  = $v->shipment_order_num;
        }


        foreach ($list as $v) {
            $spu_id = $v->id;
            //本地仓
            $v->quanzhou_num = $other_res[$spu_id]['quanzhou_num']??0;
            $v->tongan_num = $other_res[$spu_id]['tongan_num']??0;
            $v->cloud_num = $other_res[$spu_id]['cloud_num']??0;
            $v->factory_num = $other_res[$spu_id]['factory_num']??0;
            $v->deposit_num =  $other_res[$spu_id]['deposit_num']??0;
            //生产下单
            $v->out_order_num = $other_res[$spu_id]['out_order_num']??0;
            $v->shipment_order_num = $other_res[$spu_id]['shipment_order_num']??0;

            //会话率 sales_res sales_num
            $v->sales_num = $sales_res[$spu_id]??0;

            //退货 return_res return_num
            $v->return_num = $return_res[$spu_id]??0;

            //订单 order_res order_num
            $v->order_num = $order_res[$spu_id]??0;

            //fba fba_res (in_stock_num,transfer_num,in_bound_num)
            $v->in_stock_num = $fba_res[$spu_id]['in_stock_num']??0;
            $v->transfer_num = $fba_res[$spu_id]['transfer_num']??0;
            $v->in_bound_num = $fba_res[$spu_id]['in_bound_num']??0;
            //计划发货 request_res （tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）
            $v->tongan_request_num = $request_res[$spu_id]['tongan_request_num']??0;
            $v->quanzhou_request_num = $request_res[$spu_id]['quanzhou_request_num']??0;
            $v->cloud_request_num = $request_res[$spu_id]['cloud_request_num']??0;
            $v->courier_num = $request_res[$spu_id]['courier_num']??0;
            $v->shipping_num = $request_res[$spu_id]['shipping_num']??0;
            $v->air_num = $request_res[$spu_id]['air_num']??0;

            //预减后库存
            $v->tongan_deduct_inventory = $v->tongan_num - $v->tongan_request_num;
            $v->quanzhou_deduct_inventory = $v->quanzhou_num - $v->quanzhou_request_num;
            $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;
   
            //未出货
            $v->no_shipment_num = $v->shipment_order_num-$v->out_order_num;
            if($v->no_shipment_num<0){
                $v->no_shipment_num  = 0;
            }
            //转化率
            $v->conversion_rate = 0;
            //退货率
            $v->return_rate = 0;
            if($v->order_num>0){
                if( $v->sales_num>0){
                    $v->conversion_rate = round($v->order_num/$v->sales_num, 4) * 100;
                }

                if($v->return_num>0){
                    $v->return_rate = round($v->return_num/$v->order_num ,4) * 100;
                }

            }
   
            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400);
            $day_quantity_ordered = 0;
            if ($v->order_num > 0) {
                $day_quantity_ordered = round($v->order_num / $day, 2);
            }
            $v->day_quantity_ordered = $day_quantity_ordered;
   
   
            $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
            //fba仓库存
            $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
            //本地仓库存

            $v->here_inventory_day = 999;
            //本地仓库存周转天数
            $v->fba_inventory_day = 999;
            //fba仓库存周转天数
            if ($day_quantity_ordered == 0) {
                $v->here_inventory_day = 999;
                $v->fba_inventory_day = 999;
            }

            if ($v->here_inventory == 0) {
                $v->here_inventory_day = 0;
            }
            if ($v->fba_inventory == 0) {
                $v->fba_inventory_day = 0;
            }

            if ($day_quantity_ordered > 0 && $v->here_inventory > 0) {
                //本地仓库存周转天数=同安库存/日销
                $v->here_inventory_day = round($v->here_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $v->fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $v->fba_inventory_day = round($v->fba_inventory / $day_quantity_ordered, 2);
            }

            

            //补货提醒 - 本地
            //1 需要下单  2 偏多  3 冗余
            $buhuo_status_bd = 0;
            
            $bdzz = $v->here_inventory_day;
            if ($bdzz >= 0 && $bdzz < 60) {
                $buhuo_status_bd = 1;
            }
            if ($bdzz >= 60 && $bdzz < 90) {
                $buhuo_status_bd = 2;
            }
            if ($bdzz > 90) {
                $buhuo_status_bd = 3;
            }

            $fbazz =  $v->fba_inventory_day;
            //补货提醒-fba
            // $inventory_turnover = $this->inventoryTurnoverStatus($fba_inventory, $day_quantity_ordered, $plan_multiple);

            $buhuo_status_fba = 0; 
            //补货提醒更新
            if ($fbazz >= 0 && $fbazz < 60) {
                $buhuo_status_fba = 1;
            }
            if ($fbazz >= 60 && $fbazz < 90) {
                $buhuo_status_fba = 2;
            }
            if ($fbazz > 90) {
                $buhuo_status_fba = 3;
            }

            $v->buhuo_status_bd = $buhuo_status_bd; 
            $v->buhuo_status_fba = $buhuo_status_fba; 

            //补货状态  1补货过多 近两周日销*60<计划补货数量
            
            // s_day_quantity_ordered
            $v->send_status = 0;

            $courier_num  = 0;
            $shipping_num = 0;
            $air_num = 0;

            if(isset($v->courier_num)){
                $courier_num = (int)$v->courier_num;
            }

            if(isset($v->shipping_num)){
                $shipping_num = (int)$v->shipping_num;
            }
            if(isset($v->air_num)){
                $air_num = (int)$v->air_num;
            }

            $jh_buhuo = $courier_num+$shipping_num+$air_num;
            //计划发货
            if($jh_buhuo>$day_quantity_ordered*60){
                $v->send_status = 1;
            }


            //下单状态  1下单过多 近两周日销*45<未出货数量
            $v->place_order_status = 0;
            
            if($v->no_shipment_num>$day_quantity_ordered*45){
                $v->place_order_status = 1;
            }


   
            # code...
        }




        $list = json_decode(json_encode($list),true);
        


        $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';


        // $sort = $params['sort']??'order_num';
        $sort_list = array_column($list, $orderby);

        if($orderbytype=='DESC'){
            array_multisort($sort_list, SORT_DESC, $list);
        }else{
            array_multisort($sort_list, SORT_ASC, $list);
        }


        $returnlist = [];
        foreach ($list as $k => $v) {
            # code...
            for ($i=$limit * ($page-1); $i < $limit * $page; $i++) { 
                # code...
                if($k==$i){
                    $returnlist[] = $v;
                }
            }

        }

        foreach ($returnlist as &$v){
            $v['img'] = $this->GetSpuImg($v['spu']);
            if(!empty($v['old_spu'])){
                $v['spu'] = $v['old_spu'];
            }
            $v['conversion_rate'] = round($v['conversion_rate'] ,2);
            $v['return_rate'] = round($v['return_rate'] ,2);
            $v['user'] = $this->GetUsers($v['user_id'])['account'];

            $orderquery['spu_id'] = $v['id'];
            $v['fisrt_order_time'] = $this->getOrderFirst($orderquery);
        }


        return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum];
        // return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum,'total'=> $totals];
 
        //获取累加数据

    }

    //无店铺 本地（quanzhou_num，tongan_num，cloud_num，factory_num） 下单（out_order_num）  生产 （shipment_order_num） 
    //有店铺 会话率（session_percentage） 退货（return_num） 订单（order_num） fba(in_stock_num,transfer_num,in_bound_num)  计划发货（tongan_request_num，quanzhou_request_num，cloud_request_num，courier_num，shipping_num，air_num）

    //退货 
    public function getReturnByShop($params){
        $shop_id =$params['shop_id'];
        $start =$params['start'];
        $end = $params['end'];
        $type = $params['type'];
        $res = Db::table('amazon_return_order')->where('shop_id',$shop_id)->whereBetween('return_date', [$start, $end])->select(DB::raw('sum(quantity) as quantity'),$type)->groupby($type)->get();
        $return = [];
        foreach ($res as $v) {
            # code...
            if($type=='custom_sku_id'){
                $return[$v->custom_sku_id] = $v->quantity;
            }else{
                $return[$v->spu_id] = $v->quantity;
            }
            
        }
        return $return;
    }

    //订单
    public function getOrdeByShop($params){
        $shop_id =$params['shop_id'];
        $start =$params['start'];
        $end = $params['end'];
        $type = $params['type'];
        $res = Db::table('amazon_order_item')->where('shop_id',$shop_id)->whereBetween('amazon_time', [$start, $end])->select(DB::raw('sum(quantity_ordered) as quantity_ordered'),$type)->groupby($type)->get();
        $return = [];
        foreach ($res as $v) {
            # code...
            if($type=='custom_sku_id'){
                $return[$v->custom_sku_id] = $v->quantity_ordered;
            }else{
                $return[$v->spu_id] = $v->quantity_ordered;
            }
            
        }
        return $return;
    }


    //fba
    public function getFbaByShop($params){
        $shop_id =$params['shop_id'];
        $type = $params['type'];
        $return = [];
        $res = Db::table('product_detail')->where('shop_id',$shop_id)->select(DB::raw('sum(in_stock_num) as in_stock_num'),DB::raw('sum(in_bound_num) as in_bound_num'),DB::raw('sum(transfer_num) as transfer_num'),$type)->groupby($type)->get();
        foreach ($res as $v) {
            # code...
            if($type=='custom_sku_id'){
                $return[$v->custom_sku_id]['transfer_num'] = $v->transfer_num;
                $return[$v->custom_sku_id]['in_stock_num'] = $v->in_stock_num;
                $return[$v->custom_sku_id]['in_bound_num'] = $v->in_bound_num;
            }else{
                $return[$v->spu_id]['transfer_num'] = $v->transfer_num;
                $return[$v->spu_id]['in_stock_num'] = $v->in_stock_num;
                $return[$v->spu_id]['in_bound_num'] = $v->in_bound_num;
            }
        }
        return $return;
    }


    //会话率
    public function getSalesByShop($params){
        $shop_id =$params['shop_id'];
        $start =$params['start'];
        $end = $params['end'];
        $type = $params['type'];
        $res = Db::table('amazon_sale_percentage')->where('shop_id',$shop_id)->whereBetween('ds', [$start, $end])->select(DB::raw('sum(session_percentage) as session_percentage'),$type)->groupby($type)->get();
        $return = [];
        foreach ($res as $v) {
            # code...
            if($type=='custom_sku_id'){
                $return[$v->custom_sku_id] = $v->session_percentage;
            }else{
                $return[$v->spu_id] = $v->session_percentage;
            }
            
        }
        return $return;
    }

    //计划
    public function getRequestByShop($params){
        $shop_id =$params['shop_id'];
        $type = $params['type'];	
        $res = Db::table('amazon_buhuo_detail as a')->leftjoin('amazon_buhuo_request as b','a.request_id','=','b.id')->whereIn('b.request_status',[4,5,6,7])->where('a.shop_id',$shop_id)->select('a.courier_num','a.shipping_num','a.air_num','b.warehouse','a.custom_sku_id','a.spu_id')->get();
        $return = [];
        foreach ($res as $v) {
            # code...
            if($type=='custom_sku_id'){
                $total = $v->courier_num+ $v->shipping_num+ $v->air_num;
                if($v->warehouse==1){
                    if(isset($return[$v->custom_sku_id]['tongan_request_num'])){
                        $return[$v->custom_sku_id]['tongan_request_num'] += $total;
                    }else{
                        $return[$v->custom_sku_id]['tongan_request_num'] = $total;
                    }
                }
                if($v->warehouse==2){
                    if(isset($return[$v->custom_sku_id]['quanzhou_request_num'])){
                        $return[$v->custom_sku_id]['quanzhou_request_num'] += $total;
                    }else{
                        $return[$v->custom_sku_id]['quanzhou_request_num'] = $total;
                    }
                }
                if($v->warehouse==3){
                    if(isset($return[$v->custom_sku_id]['cloud_request_num'])){
                        $return[$v->custom_sku_id]['cloud_request_num'] += $total;
                    }else{
                        $return[$v->custom_sku_id]['cloud_request_num'] = $total;
                    }
                }
                if(isset($return[$v->custom_sku_id]['courier_num'])){
                    $return[$v->custom_sku_id]['courier_num'] += $v->courier_num;
                }else{
                    $return[$v->custom_sku_id]['courier_num'] = $v->courier_num;
                }
                if(isset($return[$v->custom_sku_id]['shipping_num'])){
                    $return[$v->custom_sku_id]['shipping_num'] += $v->shipping_num;
                }else{
                    $return[$v->custom_sku_id]['shipping_num'] = $v->shipping_num;
                }
                if(isset($return[$v->custom_sku_id]['air_num'])){
                    $return[$v->custom_sku_id]['air_num'] += $v->air_num;
                }else{
                    $return[$v->custom_sku_id]['air_num'] = $v->air_num;
                }
                
            }else{

                $total = $v->courier_num+ $v->shipping_num+ $v->air_num;
                if($v->warehouse==1){
                    if(isset($return[$v->spu_id]['tongan_request_num'])){
                        $return[$v->spu_id]['tongan_request_num'] += $total;
                    }else{
                        $return[$v->spu_id]['tongan_request_num'] = $total;
                    }
                }
                if($v->warehouse==2){
                    if(isset($return[$v->spu_id]['quanzhou_request_num'])){
                        $return[$v->spu_id]['quanzhou_request_num'] += $total;
                    }else{
                        $return[$v->spu_id]['quanzhou_request_num'] = $total;
                    }
                }
                if($v->warehouse==3){
                    if(isset($return[$v->spu_id]['cloud_request_num'])){
                        $return[$v->spu_id]['cloud_request_num'] += $total;
                    }else{
                        $return[$v->spu_id]['cloud_request_num'] = $total;
                    }
                }
                if(isset($return[$v->spu_id]['courier_num'])){
                    $return[$v->spu_id]['courier_num'] += $v->courier_num;
                }else{
                    $return[$v->spu_id]['courier_num'] = $v->courier_num;
                }
                if(isset($return[$v->spu_id]['shipping_num'])){
                    $return[$v->spu_id]['shipping_num'] += $v->shipping_num;
                }else{
                    $return[$v->spu_id]['shipping_num'] = $v->shipping_num;
                }
                if(isset($return[$v->spu_id]['air_num'])){
                    $return[$v->spu_id]['air_num'] += $v->air_num;
                }else{
                    $return[$v->spu_id]['air_num'] = $v->air_num;
                }
            }
            
        }
        return $return;
    }
    

    public function DataWholeSpuChangeInfo($params){

        if (isset($params['start_time'])) {
            $start = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end = $params['end_time'];
        }
        if (isset($params['find_word'])) {
            $find_word = $params['find_word'];
        }
        if (isset($params['spu_id'])) {
            $spu_id = $params['spu_id'];
        }
        

        $start_time = isset($start) ? $start : date('Y-m-d', time());
        $end_time = isset($end) ? $end : date('Y-m-d', time());

        $end_time = $end_time.' 23:59:59';


        // DB::connection()->enableQueryLog();

        $caches = Db::table('cache_spu')->whereBetween('ds', [$start_time, $end_time])->where('spu_id',$spu_id)->select($find_word,'ds')->get();
        //   print_r(DB::getQueryLog());
        return ['type'=>'success','data'=> $caches];
    }


    //1
    
    public function DatawholeSpuNew($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        
        //初始化查询
        $thisDb = Db::table('self_spu as a')->leftjoin('self_base_spu as b','a.base_spu_id','=','b.id');


        if (isset($params['user_id'])) {
            $thisDb = $thisDb->whereIn('a.operate_user_id',$params['user_id']);
        }
        if (isset($params['spu'])) {
            $thisDb = $thisDb->where('a.spu','like','%'.$params['spu'].'%')->orWhere('a.old_spu','like','%'.$params['spu'].'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->whereIn('b.three_cate_id',$params['three_cate_id']);
        }

        if(isset($params['color_style'])){
            $thisDb = $thisDb->where('b.color_style','=',$params['color_style']);
        }

        if(isset($params['seasonal_style'])){
            $thisDb = $thisDb->where('b.seasonal_style','=',$params['seasonal_style']);
        }


        if(isset($params['fabric_composition'])){
            $thisDb = $thisDb->where('b.fabric_composition','=',$params['fabric_composition']);
        }


        if (isset($params['start_time'])) {
            $start = $params['start_time'];
        }
        if (isset($params['end_time'])) {
            $end = $params['end_time'];
        }

        $start_time = isset($start) ? $start : date('Y-m-d', time());
        $end_time = isset($end) ? $end : date('Y-m-d', time());

        $end_time = $end_time.' 23:59:59';
        $today = date('Y-m-d',time());
        $totalNum=$thisDb->where('a.type',1)->count();

  
        $list = $thisDb
        ->where('a.type',1)
        ->select('a.id','a.spu','a.old_spu','a.create_time','a.sales_status','b.user_id as create_user_id','a.plan_multiple','b.one_cate_id','b.three_cate_id','a.operate_user_id as user_id','b.id as base_spu_id','b.color_style','b.seasonal_style','b.fabric_composition')
        ->orderby('a.id','DESC')
        ->get();
 
        //获取累加数据

        $caches = Db::table('cache_spu')->whereBetween('ds', [$start_time, $end_time])->get();

        $spu_cache = [];
        foreach ($caches as $v) {
            # code...
            if(isset($spu_cache[$v->spu_id]['order_num'])){
                $spu_cache[$v->spu_id]['order_num'] +=$v->order_num;
            }else{
                $spu_cache[$v->spu_id]['order_num'] = $v->order_num;
            }
            if(isset($spu_cache[$v->spu_id]['session_percentage'])){
                $spu_cache[$v->spu_id]['session_percentage'] +=$v->session_percentage;
            }else{
                $spu_cache[$v->spu_id]['session_percentage'] =$v->session_percentage;
            }
            if(isset($spu_cache[$v->spu_id]['return_num'])){
                $spu_cache[$v->spu_id]['return_num'] +=$v->return_num;
            }else{
                $spu_cache[$v->spu_id]['return_num']=$v->return_num;
            }
            $spu_cache[$v->spu_id]['spu_id'] = $v->spu_id;
        }

        // $spu_cache = array_values($spu_cache);

        
        //获取实时数据
        $cachetodayss = Db::table('cache_spu')->where('ds','like', "{$today}%")->get();
        $cachetodays = [];
        foreach ($cachetodayss as $v) {
            # code...
            $cachetodays[$v->spu_id] = $v;
        }


        //
        $total_order = 0;
        $total_return = 0;
        $total_inventory_quanzhou = 0;
        $total_inventory_tongan = 0;
        $total_inventory_deposit = 0;
        $total_cloud_tongan = 0;
        $total_in_stock_num = 0;
        $total_transfer_num = 0;
        $total_in_bound_num = 0;
        $total_tongan_request_num = 0;
        $total_quanzhou_request_num = 0;
        $total_cloud_request_num = 0;
        $total_courier_num = 0;//计划快递发货
        $total_shipping_num = 0;//计划海运发货
        $total_air_num = 0;//计划空运发货

        $total_shipment_order_num = 0; //生产下单数据
        $total_out_order_num = 0; //已出货
        $total_tongan_deduct_inventory = 0;
        $total_quanzhou_deduct_inventory = 0;
        $total_cloud_deduct_inventory = 0;

        $total_inventory = 0;


        $new_update_time = date('Y-m-d',time());

        $orderby = isset($params['od']) ? $params['od'] : 'order_num';

        $post_spu_ids = [];

        //断点1 1.06s
        
        foreach ($list as $k=>$v) {
            # code...
            $post_spu_ids[] = $v->id;

            $v->session_percentage = 0;
            $v->return_num = 0;
            $v->order_num = 0;
            $v->factory_num = 0;
            if(isset($spu_cache[$v->id])){
                        $v->order_num =$spu_cache[$v->id]['order_num'];
                        $v->session_percentage =$spu_cache[$v->id]['session_percentage'];
                        $v->return_num =$spu_cache[$v->id]['return_num'];
            }
            // if($spu_cache){
            //     foreach ($spu_cache as $cv) {
            //         # code...
            //         if($cv['spu_id'] == $v->id){
            //             $v->order_num =$cv['order_num'];
            //             $v->session_percentage =$cv['session_percentage'];
            //             $v->return_num =$cv['return_num'];
            //         }
            //     }
            // }

    

            $v->in_stock_num = 0;//fba在仓库存
            $v->transfer_num = 0;//预留库存
            $v->in_bound_num = 0;//在途库存
            $v->quanzhou_num = 0;
            $v->tongan_num = 0;
            $v->cloud_num = 0;

            $v->deposit_num = 0;

            $v->tongan_request_num = 0;//同安计划中总数
            $v->quanzhou_request_num = 0;//泉州计划中总数
            $v->cloud_request_num = 0;//云仓计划中总数

            $v->courier_num = 0;//计划快递发货
            $v->shipping_num = 0;//计划海运发货
            $v->air_num = 0;//计划空运发货


            $v->shipment_order_num = 0; //生产下单数据
            $v->out_order_num = 0; //已出货

            if(isset($cachetodays[$v->id])){
             $cachetoday =  $cachetodays[$v->id];
            //    if(!isset($new_update_time)){
            //      $new_update_time = $cachet_one['update_time'];
            //    }

               
            //    $v->factory_num = $cachet_one['factory_num'];
            //    $v->in_stock_num = $cachet_one['in_stock_num'];
            //    $v->transfer_num = $cachet_one['transfer_num'];
            //    $v->in_bound_num = $cachet_one['in_bound_num'];
            //    $v->quanzhou_num = $cachet_one['quanzhou_num'];
            //    $v->tongan_num = $cachet_one['tongan_num'];
            //    $v->cloud_num = $cachet_one['cloud_num'];

            //    $v->deposit_num = $cachet_one['deposit_num'];

            //    $v->tongan_request_num = $cachet_one['tongan_request_num'];
            //    $v->quanzhou_request_num = $cachet_one['quanzhou_request_num'];
            //    $v->cloud_request_num = $cachet_one['cloud_request_num'];
   
            //    $v->courier_num = $cachet_one['factocourier_numry_num'];
            //    $v->shipping_num = $cachet_one['shipping_num'];
            //    $v->air_num = $cachet_one['air_num'];

            //    $v->shipment_order_num = $cachet_one['shipment_order_num'];
            //    $v->out_order_num = $cachet_one['out_order_num'];
                    if(!isset($new_update_time)){
                        $new_update_time = $cachetoday->update_time;
                    }
                    # code...
                    if($v->id == $cachetoday->spu_id){

                        $v->factory_num = $cachetoday->factory_num;
                        $v->in_stock_num = $cachetoday->in_stock_num;
                        $v->transfer_num = $cachetoday->transfer_num;
                        $v->in_bound_num = $cachetoday->in_bound_num;
                        $v->quanzhou_num = $cachetoday->quanzhou_num;
                        $v->tongan_num = $cachetoday->tongan_num;
                        $v->cloud_num = $cachetoday->cloud_num;

                        $v->deposit_num = $cachetoday->deposit_num;
    
                        $v->tongan_request_num = $cachetoday->tongan_request_num;
                        $v->quanzhou_request_num = $cachetoday->quanzhou_request_num;
                        $v->cloud_request_num = $cachetoday->cloud_request_num;
            
                        $v->courier_num = $cachetoday->courier_num;
                        $v->shipping_num = $cachetoday->shipping_num;
                        $v->air_num = $cachetoday->air_num;
    
                        $v->shipment_order_num = $cachetoday->shipment_order_num;
                        $v->out_order_num = $cachetoday->out_order_num;
                    }

            }

            // if($cachetodays){
            //     foreach ($cachetodays as $cachetoday) {
            //         if(!isset($new_update_time)){
            //             $new_update_time = $cachetoday->update_time;
            //         }
            //         # code...
            //         if($v->id == $cachetoday->spu_id){

            //             $v->factory_num = $cachetoday->factory_num;
            //             $v->in_stock_num = $cachetoday->in_stock_num;
            //             $v->transfer_num = $cachetoday->transfer_num;
            //             $v->in_bound_num = $cachetoday->in_bound_num;
            //             $v->quanzhou_num = $cachetoday->quanzhou_num;
            //             $v->tongan_num = $cachetoday->tongan_num;
            //             $v->cloud_num = $cachetoday->cloud_num;

            //             $v->deposit_num = $cachetoday->deposit_num;
    
            //             $v->tongan_request_num = $cachetoday->tongan_request_num;
            //             $v->quanzhou_request_num = $cachetoday->quanzhou_request_num;
            //             $v->cloud_request_num = $cachetoday->cloud_request_num;
            
            //             $v->courier_num = $cachetoday->courier_num;
            //             $v->shipping_num = $cachetoday->shipping_num;
            //             $v->air_num = $cachetoday->air_num;
    
            //             $v->shipment_order_num = $cachetoday->shipment_order_num;
            //             $v->out_order_num = $cachetoday->out_order_num;
            //         }
            //     }
            // }

            //预减后库存
            $v->tongan_deduct_inventory = $v->tongan_num - $v->tongan_request_num;
            $v->quanzhou_deduct_inventory = $v->quanzhou_num - $v->quanzhou_request_num;
            $v->cloud_deduct_inventory =  $v->cloud_num - $v->cloud_request_num;

            $v->no_shipment_num = $v->shipment_order_num-$v->out_order_num;
            if($v->no_shipment_num<0){
                $v->no_shipment_num  = 0;
            }
            //转化率
            $v->conversion_rate = 0;
            //退货率
            $v->return_rate = 0;
            if($v->order_num>0){
                if( $v->session_percentage>0){
                    $v->conversion_rate = round($v->order_num/$v->session_percentage, 4) * 100;
                }

                if($v->return_num>0){
                    $v->return_rate = round($v->return_num/$v->order_num ,4) * 100;
                }

            }

            $v->conversion_rate_e = $v->conversion_rate.'%';
            $v->return_rate_e = $v->return_rate.'%';


            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400);
            $day_quantity_ordered = 0;
            if ($v->order_num > 0) {
                $day_quantity_ordered = round($v->order_num / $day, 2);
            }
            $v->day_quantity_ordered = $day_quantity_ordered;


            $v->fba_inventory =$v->in_stock_num + $v->transfer_num + $v->in_bound_num;
            //fba仓库存
            $v->here_inventory = $v->tongan_num + $v->quanzhou_num + $v->cloud_num;
            //本地仓库存

            $v->here_inventory_day = 999;
            //本地仓库存周转天数
            $v->fba_inventory_day = 999;
            //fba仓库存周转天数
            if ($day_quantity_ordered == 0) {
                $v->here_inventory_day = 999;
                $v->fba_inventory_day = 999;
            }

            if ($v->here_inventory == 0) {
                $v->here_inventory_day = 0;
            }
            if ($v->fba_inventory == 0) {
                $v->fba_inventory_day = 0;
            }

            if ($day_quantity_ordered > 0 && $v->here_inventory > 0) {
                //本地仓库存周转天数=同安库存/日销
                $v->here_inventory_day = round($v->here_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $v->fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $v->fba_inventory_day = round($v->fba_inventory / $day_quantity_ordered, 2);
            }

            //补货提醒 - 本地
            //1 需要下单  2 偏多  3 冗余
            $buhuo_status_bd = 0;
            
            $bdzz = $v->here_inventory_day;
            if ($bdzz >= 0 && $bdzz < 60) {
                $buhuo_status_bd = 1;
            }
            if ($bdzz >= 60 && $bdzz < 90) {
                $buhuo_status_bd = 2;
            }
            if ($bdzz > 90) {
                $buhuo_status_bd = 3;
            }

            $fbazz =  $v->fba_inventory_day;
            //补货提醒-fba
            // $inventory_turnover = $this->inventoryTurnoverStatus($fba_inventory, $day_quantity_ordered, $plan_multiple);

            $buhuo_status_fba = 0; 
            //补货提醒更新
            if ($fbazz >= 0 && $fbazz < 60) {
                $buhuo_status_fba = 1;
            }
            if ($fbazz >= 60 && $fbazz < 90) {
                $buhuo_status_fba = 2;
            }
            if ($fbazz > 90) {
                $buhuo_status_fba = 3;
            }

            $v->buhuo_status_bd = $buhuo_status_bd; 
            $v->buhuo_status_fba = $buhuo_status_fba; 

            //补货状态  1补货过多 近两周日销*60<计划补货数量
            
            // s_day_quantity_ordered
            $v->send_status = 0;

            $courier_num  = 0;
            $shipping_num = 0;
            $air_num = 0;

            if(isset($v->courier_num)){
                $courier_num = (int)$v->courier_num;
            }

            if(isset($v->shipping_num)){
                $shipping_num = (int)$v->shipping_num;
            }
            if(isset($v->air_num)){
                $air_num = (int)$v->air_num;
            }

            $jh_buhuo = $courier_num+$shipping_num+$air_num;
            //计划发货
            if($jh_buhuo>$day_quantity_ordered*60){
                $v->send_status = 1;
            }


            //下单状态  1下单过多 近两周日销*45<未出货数量
            $v->place_order_status = 0;
            
            if($v->no_shipment_num>$day_quantity_ordered*45){
                $v->place_order_status = 1;
            }


            $v->total_inventory =  $v->fba_inventory + $v->here_inventory + $v->factory_num;


            $total_inventory+= $v->total_inventory;


            $total_order += $v->order_num;
            $total_return += $v->return_num;
            $total_inventory_quanzhou += $v->quanzhou_num;
            $total_inventory_tongan += $v->tongan_num;
            $total_inventory_deposit += $v->deposit_num;
            $total_cloud_tongan += $v->cloud_num;
            $total_in_stock_num += $v->in_stock_num;
            $total_transfer_num += $v->transfer_num;
            $total_in_bound_num += $v->in_bound_num;
            $total_tongan_request_num += $v->tongan_request_num;
            $total_quanzhou_request_num += $v->quanzhou_request_num;
            $total_cloud_request_num += $v->cloud_request_num;
            $total_courier_num += $v->courier_num;
            $total_shipping_num += $v->shipping_num;
            $total_air_num += $v->air_num;

            $total_shipment_order_num += $v->shipment_order_num;
            $total_out_order_num += $v->out_order_num;
            $total_tongan_deduct_inventory+= $v->tongan_deduct_inventory;
            $total_quanzhou_deduct_inventory += $v->quanzhou_deduct_inventory;
            $total_cloud_deduct_inventory+= $v->cloud_deduct_inventory;
            $orderquery['spu_id'] = $v->id;
            $v->fisrt_order_time = '';
            // $v->fisrt_order_time = $this->getOrderFirst($orderquery);

            if($orderby=='fisrt_order_time'){
                if($v->total_inventory<=0&&$v->fisrt_order_time==''){
                    unset($list[$k]);
                }
            }
        }

        //断点2 1.06s



        $total_no_shipment_num = $total_shipment_order_num-$total_out_order_num;
        $totals['total_inventory'] =  $total_inventory;
        $totals['order_num'] =  $total_order;
        $totals['return_num'] =  $total_return;
        $totals['quanzhou_num'] =  $total_inventory_quanzhou;
        $totals['deposit_num'] =  $total_inventory_deposit;
        $totals['tongan_num'] =  $total_inventory_tongan;
        $totals['cloud_num'] =  $total_cloud_tongan;
        $totals['in_stock_num'] =  $total_in_stock_num;
        $totals['transfer_num'] =  $total_transfer_num;
        $totals['in_bound_num'] =  $total_in_bound_num;
        $totals['tongan_request_num'] =  $total_tongan_request_num;
        $totals['quanzhou_request_num'] =  $total_quanzhou_request_num;
        $totals['cloud_request_num'] =  $total_cloud_request_num;
        $totals['courier_num'] =  $total_courier_num;
        $totals['shipping_num'] =  $total_shipping_num;
        $totals['air_num'] =  $total_air_num;
        $totals['shipment_order_num'] =  $total_shipment_order_num;
        $totals['out_order_num'] =  $total_out_order_num;
        $totals['tongan_deduct_inventory'] =  $total_tongan_deduct_inventory;
        $totals['quanzhou_deduct_inventory'] =  $total_quanzhou_deduct_inventory;
        $totals['cloud_deduct_inventory'] =  $total_cloud_deduct_inventory;
        $totals['no_shipment_num'] =  $total_no_shipment_num;



        $list = json_decode(json_encode($list),true);
        


        // $orderby = isset($params['od']) ? $params['od'] : 'order_num';
        $orderbytype =  isset($params['odt']) ? $params['odt'] : 'DESC';


        // $sort = $params['sort']??'order_num';
        $sort_list = array_column($list, $orderby);

        if($orderbytype=='DESC'){
            array_multisort($sort_list, SORT_DESC, $list);
        }else{
            array_multisort($sort_list, SORT_ASC, $list);
        }

        $posttype = 1;
        if(isset($params['posttype'])){
            $posttype = $params['posttype'];
        }
    
                

        if($posttype==2){

            
            //会话率查询
            $sessions_total = [];
            $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('spu_id',$post_spu_ids)->where('sessions_total','>',0)->groupby('spu_id')->select('spu_id',db::raw('sum(sessions_total) as sessions_total'))->get();

            foreach ($sessions_res as $srv) {
                # code...
                $sessions_total[$srv->spu_id] = $srv->sessions_total;
            }

            foreach ($list as &$v){
                $v['img'] = $this->GetBaseSpuImg($v['base_spu_id']);
                if(!empty($v['old_spu'])){
                    $v['spu'] = $v['old_spu'];
                }
                
                //转化率 = 销量/总会话量
                $v['conversion_rate'] = 0;

                $sessions = 0;
                if(isset($sessions_total[$v['id']])){
                    $sessions = $sessions_total[$v['id']];
                }

                if($sessions>0&&$v['order_num']>0){
                    $v['conversion_rate'] = round(($v['order_num']/$sessions)*100,2);
                }
                $v['conversion_rate_e'] =  $v['conversion_rate'].'%';



                // $v['conversion_rate'] = round($v['conversion_rate'] ,2);
                $v['return_rate'] = round($v['return_rate'] ,2);

                $v['return_rate_e'] =  $v['return_rate'].'%';
                
                $v['user'] = $this->GetUsers($v['user_id'])['account'];
                $v['create_user'] = $this->GetUsers($v['create_user_id'])['account'];
    
                $last_year_query['start_time'] = $start_time;
                $last_year_query['end_time'] = $end_time;
                $last_year_query['spu_id'] = $v['id'];
    
                $v['last_year_order_num'] = $this->GetOrderLastYear($last_year_query);
    
                // $orderquery['spu_id'] = $v['id'];
                // $v['fisrt_order_time'] = $this->getOrderFirst($orderquery);
            }

                  
            $p['title']='spu数据报表'.time();

            $listtlt = [
                'spu'=>'spu',
                'user' => '产品开发人员',
                'create_user' => '创建者',
                'day_quantity_ordered'=>'日销',
                'order_num'=>$start_time.'-'.$end_time.'销售',
                'last_year_order_num'=>'去年销售',
                'conversion_rate_e'=>'转化率',
                'return_rate_e'=>'退货率',
                'return_num'=>'退货数量',
                'tongan_num'=>'同安仓库存',
                'quanzhou_num'=>'泉州仓库存',
                'deposit_num'=>'工厂寄存仓',
                'cloud_num'=>'云仓库存',
                'factory_num'=>'工厂虚拟仓库存',
                'total_inventory'=>'总库存',
                'in_stock_num'=>'fba在仓',
                'transfer_num'=>'fba预留',
                'in_bound_num'=>'fba在途',
                'here_inventory_day'=>'本地仓周转天数',
                'fba_inventory_day'=>'fba仓周转天数',
                'fisrt_order_time'=>'首单时间',
            ];

    
            $p['title_list']  = $listtlt;
            $p['data'] =   $list;
            $p['user_id'] =  $params['find_user_id']??1;  
            $p['type'] = 'spu数据报表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }

        $spu_ids = [];
        $returnlist = [];
        foreach ($list as $k => $v) {
            # code...
            for ($i=$limit * ($page-1); $i < $limit * $page; $i++) { 
                # code...
                if($k==$i){
                    $returnlist[] = $v;
                    $spu_ids[] = $v['id'];
                }
            }

        }
        // return ['type' => 'success','msg' => '加入队列成功4'];

        //会话率查询
        // $sessions_total = [];
        // $sessions_res = db::table('lingxing_product_expression')->whereBetween('date', [$start_time, $end_time])->whereIn('spu_id',$spu_ids)->where('sessions_total','>',0)->groupby('spu_id')->select('spu_id',db::raw('sum(sessions_total) as sessions_total'))->get();

        // foreach ($sessions_res as $srv) {
        //     # code...
        //     $sessions_total[$srv->spu_id] = $srv->sessions_total;
        // }



        foreach ($returnlist as &$v){
            $v['img'] = $this->GetBaseSpuImg($v['base_spu_id']);
            if(!empty($v['old_spu'])){
                $v['spu'] = $v['old_spu'];
            }



            //转化率 = 销量/总会话量
            $v['conversion_rate'] = 0;

            $sessions = 0;
            // if(isset($sessions_total[$v['id']])){
            //     $sessions = $sessions_total[$v['id']];
            // }
            $sessions =  db::table('lingxing_product_expression')->where('spu_id',$v['id'])->whereBetween('date', [$start_time, $end_time])->sum('sessions_total');
            if($sessions>0&&$v['order_num']>0){
                $v['conversion_rate'] = round(($v['order_num']/$sessions)*100,2);
            }



            // $v['conversion_rate'] = round($v['conversion_rate'] ,2);
            $v['return_rate'] = round($v['return_rate'] ,2);
            $v['user'] = $this->GetUsers($v['user_id'])['account'];
            $v['create_user'] = $this->GetUsers($v['create_user_id'])['account'];
            $v['create_time'] = date('Y-m-d',$v['create_time']);

            $last_year_query['start_time'] = $start_time;
            $last_year_query['end_time'] = $end_time;
            $last_year_query['spu_id'] = $v['id'];

            $v['last_year_order_num'] = $this->GetOrderLastYear($last_year_query);

            // $orderquery['spu_id'] = $v['id'];
            // $v['fisrt_order_time'] = $this->getOrderFirst($orderquery);
        }
      
        // foreach ($returnlist as &$v) {
        //     $spu_id = $v['id'];
        //     //出入库时间
        //     //出
        //     //同安
        //     if(isset($params['shop_id'])){
        //         $shop_id = $params['shop_id'];
        //     }
        //     if(isset($params['shop_id'])){
        //         $outSql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and warehouse_id in(2,386) and type =1 and shop_id = {$shop_id} order by max desc limit 1 ";
        //     }else{
        //         $outSql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and warehouse_id in(2,386) and type =1 order by max desc limit 1 ";
        //     }
        
        //     $outData1 = DB::select($outSql1);
        //     //泉州
        //     if(isset($params['shop_id'])){
        //         $outSql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and warehouse_id=560 and type =1 and shop_id = {$shop_id} order by max desc limit 1 ";
        //     }else{
        //         $outSql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and warehouse_id=560 and type =1 order by max desc limit 1 ";
        //     }
        //     $outData2 = DB::select($outSql2);
        //     //万翔

        //     $outSql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where spu_id={$spu_id} and type =1 order by max desc limit 1 ";
            

        //     $outData3 = DB::select($outSql3);
        //     //入
        //     //同安
        //     if(isset($params['shop_id'])){
        //         $insql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and type =2 and shop_id = {$shop_id} order by max desc limit 1 ";
        //     }else{
        //         $insql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where spu_id={$spu_id} and type =2 order by max desc limit 1 ";
        //     }

        //     $inData1 = DB::select($insql1);
        //     //泉州
        //     if(isset($params['shop_id'])){
        //         $insql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where  spu_id={$spu_id} and type =2 and shop_id = {$shop_id} order by max desc limit 1 ";
        //     }else{
        //         $insql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where  spu_id={$spu_id} and type =2 order by max desc limit 1 ";
        //     }

        //     $inData2 = DB::select($insql2);
        //     //万翔

        //     $insql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where spu_id={$spu_id} and type =2 order by max desc limit 1 ";    

        //     $inData3 = DB::select($insql3);

        //     $v['out1'] = isset($outData1[0]) ? date('Y-m-d', strtotime($outData1[0]->operation_date)) : '';
        //     $v['out2'] = isset($outData2[0]) ? date('Y-m-d', strtotime($outData2[0]->operation_date)) : '';
        //     $v['out3']  = isset($outData3[0]) ? date('Y-m-d', strtotime($outData3[0]->createtime)) : '';
        //     $v['in1'] = isset($inData1[0]) ? date('Y-m-d', strtotime($inData1[0]->operation_date)) : '';
        //     $v['in2']= isset($inData2[0]) ? date('Y-m-d', strtotime($inData2[0]->operation_date)) : '';
        //     $v['in3']= isset($inData3[0]) ? date('Y-m-d', strtotime($inData3[0]->createtime)) : '';
        // }


        return ['type'=>'success','data' => $returnlist,'totalnum' => $totalNum,'total'=> $totals,'last_update_time'=>$new_update_time];
    }

    public function GetOrderLastYear($params){
        $start_time = $params['start_time'];
        $end_time = $params['end_time'];
        $start_time = date('Y-m-d', strtotime("$start_time -1 year"));
        $end_time = date('Y-m-d 23:59:59', strtotime("$end_time -1 year"));
        $spu_id = $params['spu_id'];
        // DB::connection()->enableQueryLog();
        $order_num = Db::table('amazon_order_item')->where('spu_id',$spu_id)->whereBetween('amazon_time',[$start_time, $end_time])->where('order_status','!=','Canceled')->sum('quantity_ordered');
        // var_dump(DB::getQueryLog());
        return $order_num;
    }

    //清楚缓存锁-立即执行缓存
    public function runCache($params){
        $type = $params['type']??1;

        switch ($type) {
            case 1:
                # code...
                //spu报表缓存
                Redis::Del('datalock:go-cache-spu-lock');
                break;
            
            case 2:
                //库存sku缓存
                Redis::Del('datalock:go-cache-cus-lock');
                # code...
                break;
            case 3:
                //补货预警缓存
                Redis::Del('datalock:go-buhuo-lock');
                # code...
                break;
        }

        return ['type'=>'success','msg'=>'删除成功'];
    }


    
    public function getDatawholeSpu($params)
    {
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        //分页
        $pagenNum=$page-1;
        if ($pagenNum != 0) {
            $pagenNum = $limit * $pagenNum;
        }


        $limitcount  =  Db::table('self_spu')->count();

        $pi =  round($limitcount/30);
        // echo $pi;

        if($limit>= $limitcount-($limitcount*0.1)){

                if(!isset($params['spu'])&&!isset($params['one_cate_id'])&&!isset($params['two_cate_id'])&&!isset($params['three_cate_id'])){
                    //不存在搜索条件时

                    $return = [];
                    for ($i=1; $i < $pi+2; $i++) { 
                        # code...
                        $rk = 'datawhole_spu:'.$params['start_time'].$params['end_time'].'page'.$i;
                        // echo $rk;
                        $datas = Redis::Get($rk);
                        if($datas){
                            $nds = json_decode($datas,true);
                           
                            $ndsb = [];
                            foreach ($nds['data'] as $ndk => $ndv) {
                                # code...
                                $ndsb[$i.'-'.$ndk] = $ndv;
                            }                            
                            $return+=$ndsb;
                        }

                    }


                    $posttype = $params['posttype']??1;

                    if($posttype==2){
                        $p['title']='spu报表';
                        $p['title_list']  = [
                            'spu'=>'spu',
                            'cate_name'=>'品类',
                            'buhuo_status_bd'=>'补货提醒-本地',
                            'buhuo_status_fba'=>'补货提醒-fba',
                            'send_status'=>'补货状态',
                            'place_order_status'=>'下单状态',
                            'quantity_ordered'=>$params['start_time'].'-'.$params['end_time'].'销售',
                            'conversion_rate'=>'转化率',
                            'return_num'=>'退货数量',
                            'return_rate'=>'退货率',
                            'tongAn_inventory'=>'同安库存',
                            'tongAn_deduct_inventory'=>'预减后同安仓库存',
                            'quanzhou_inventory'=>'泉州仓库存',
                            'quanzhou_deduct_inventory'=>'预减后泉州仓库存',
                            'cloud_inventory'=>'云仓库存',
                            'cloud_deduct_inventory'=>'预减后云仓库存',
                            'in_warehouse_inventory'=>'fba在仓',
                            'reserved_inventory'=>'fba预留',
                            'in_road_inventory'=>'fba在途',
                            'shipping_num'=>'计划海运',
                            'air_num'=>'计划空运',
                            'courier_num'=>'计划快递',
                            'out1'=>'出仓时间-同安',
                            'out2'=>'出仓时间-泉州',
                            'out3'=>'出仓时间-云仓',
                            'in1'=>'入仓时间-同安',
                            'in2'=>'入仓时间-泉州',
                            'in3'=>'入仓时间-云仓',
                            'fba_inventory'=>'周转天数-fba',
                            'here_inventory_day'=>'周转天数-本地',
                            'order_num'=>'总下单',
                            'shipment_num'=>'已出货',
                            'no_shipment_num'=>'未出货',
                        ];
            
            
                        $p['data'] = $return;
            
                        foreach ($p['data'] as &$v) {
                            //1 需要补货  2 库存偏多  3 库存冗余
                            if($v['buhuo_status_bd']==1){
                                $v['buhuo_status_bd'] = '需要补货';
                            }elseif($v['buhuo_status_bd']==2){
                                $v['buhuo_status_bd'] = '库存偏多';
                            }elseif($v['buhuo_status_bd']==3){
                                $v['buhuo_status_bd'] = '库存冗余';
                            }
            
            
                            //1 需要补货  2 库存偏多  3 库存冗余
                            if($v['buhuo_status_fba']==1){
                                $v['buhuo_status_fba'] = '需要补货';
                            }elseif($v['buhuo_status_fba']==2){
                                $v['buhuo_status_fba'] = '库存偏多';
                            }elseif($v['buhuo_status_fba']==3){
                                $v['buhuo_status_fba'] = '库存冗余';
                            }
            
            
                            if($v['send_status']==1){
                                $v['send_status'] = '过多';
                            }else{
                                $v['send_status'] = '正常';
                            }
            
                            if($v['place_order_status']==1){
                                $v['place_order_status'] = '过多';
                            }else{
                                $v['place_order_status'] = '正常';
                            }
            
                        }
            
                        $this->excel_expord($p);
                    }

                    return [
                        'data' => array_values($return),
                        'totalnum' => count($return),
                    ];
                    
                }


              

        }


        //初始化查询
        $thisDb = Db::table('self_spu');
        if (isset($params['spu'])) {
            $thisDb = $thisDb->where('spu','like','%'.$params['spu'].'%')->orWhere('old_spu','like','%'.$params['spu'].'%');
        }
        if(isset($params['one_cate_id'])){
            $thisDb = $thisDb->where('one_cate_id','=',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $thisDb = $thisDb->where('two_cate_id','=',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $thisDb = $thisDb->where('three_cate_id','=',$params['three_cate_id']);
        }
        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }

        if(!isset($params['spu'])&&!isset($params['one_cate_id'])&&!isset($params['two_cate_id'])&&!isset($params['three_cate_id'])&&!isset($params['shop_id'])){
            //不存在搜索条件时
            $datas = Redis::Get('datawhole_spu:'.$params['start_time'].$params['end_time'].'page'.$page);
            if($datas){

                $posttype = $params['posttype']??1;

        

                if($posttype==2){
        
                    $p['title']='spu报表';
                    $p['title_list']  = [
                        'spu'=>'spu',
                        'cate_name'=>'品类',
                        'buhuo_status_bd'=>'补货提醒-本地',
                        'buhuo_status_fba'=>'补货提醒-fba',
                        'send_status'=>'补货状态',
                        'place_order_status'=>'下单状态',
                        'quantity_ordered'=>$params['start_time'].'-'.$params['end_time'].'销售',
                        'conversion_rate'=>'转化率',
                        'return_num'=>'退货数量',
                        'return_rate'=>'退货率',
                        'tongAn_inventory'=>'同安库存',
                        'tongAn_deduct_inventory'=>'预减后同安仓库存',
                        'quanzhou_inventory'=>'泉州仓库存',
                        'quanzhou_deduct_inventory'=>'预减后泉州仓库存',
                        'cloud_inventory'=>'云仓库存',
                        'cloud_deduct_inventory'=>'预减后云仓库存',
                        'in_warehouse_inventory'=>'fba在仓',
                        'reserved_inventory'=>'fba预留',
                        'in_road_inventory'=>'fba在途',
                        'shipping_num'=>'计划海运',
                        'air_num'=>'计划空运',
                        'courier_num'=>'计划快递',
                        'out1'=>'出仓时间-同安',
                        'out2'=>'出仓时间-泉州',
                        'out3'=>'出仓时间-云仓',
                        'in1'=>'入仓时间-同安',
                        'in2'=>'入仓时间-泉州',
                        'in3'=>'入仓时间-云仓',
                        'fba_inventory'=>'周转天数-fba',
                        'here_inventory_day'=>'周转天数-本地',
                        'order_num'=>'总下单',
                        'shipment_num'=>'已出货',
                        'no_shipment_num'=>'未出货',
                    ];
        
                    // $p['data'] = $spu;
                    $p['data'] = json_decode($datas,true)['data'];
        
                    foreach ($p['data'] as $v) {
                        //1 需要补货  2 库存偏多  3 库存冗余
                        if($v['buhuo_status_bd']==1){
                            $v['buhuo_status_bd'] = '需要补货';
                        }elseif($v['buhuo_status_bd']==2){
                            $v['buhuo_status_bd'] = '库存偏多';
                        }elseif($v['buhuo_status_bd']==3){
                            $v['buhuo_status_bd'] = '库存冗余';
                        }
        
        
                        //1 需要补货  2 库存偏多  3 库存冗余
                        if($v['buhuo_status_fba']==1){
                            $v['buhuo_status_fba'] = '需要补货';
                        }elseif($v['buhuo_status_fba']==2){
                            $v['buhuo_status_fba'] = '库存偏多';
                        }elseif($v['buhuo_status_fba']==3){
                            $v['buhuo_status_fba'] = '库存冗余';
                        }
        
        
                        if($v['send_status']==1){
                            $v['send_status'] = '过多';
                        }else{
                            $v['send_status'] = '正常';
                        }
        
                        if($v['place_order_status']==1){
                            $v['place_order_status'] = '过多';
                        }else{
                            $v['place_order_status'] = '正常';
                        }
        
        
                    }
        
                    // var_dump($p);
                    // exit;
                    $this->excel_expord($p);
                }



                $return = json_decode($datas,true);

                return [
                    'data' => $return['data'],
                    'totalnum' => $return['total'],
                ];
            }
        }

        //数据总数
        $totalNum=$thisDb->count();
        $spu = $thisDb
            ->offset($pagenNum)
            ->limit($limit)
            ->select('id','spu','old_spu','sales_status','plan_multiple','one_cate_id','three_cate_id')
            ->orderby('spu','ASC')
            ->get()
            ->toArray();

        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());
        if (empty($spu)) {
            return [
                'data' => [],
                'totalnum' => 0,
            ];
        }
        $spu_arr = array_column($spu, 'spu');
        // $old_spu_arr = array_column($spu, 'old_spu');

        // $spu_arr = array_merge($old_spu_arr,$new_spu_arr);
        //退货数量拼接数组spu=>数量
        // $where = [
        //     ['id','>',1]
        // ];
        $where=[];
        if(isset($params['shop_id'])){
            $where['shop_id'] = $params['shop_id'];
        }

        $returnArr = [];
        $return_order = DB::table('amazon_return_order')
            ->whereIn('spu',$spu_arr)
            ->whereBetween('beijing_date', [$start_time, $end_time])
            ->where($where)
            ->select('spu','quantity')
            ->get()
            ->toArray();
        foreach ($return_order as $reVal){
            if(isset($returnArr[$reVal->spu])){
                $returnArr[$reVal->spu] += $reVal->quantity;
            }else{
                $returnArr[$reVal->spu] = $reVal->quantity;
            }
        }

        // //图片数据数组拼接spu=>图片地址
        // $img_arr = [];
        $cloud_inventory = [];//云仓库存
        $sku_img = DB::table('self_custom_sku')->whereIn('spu',$spu_arr)->select('spu','cloud_num')->get()->toArray();


        foreach ($sku_img as $imgVal){
            // $img_arr[$imgVal->spu] = $imgVal->img;
            if(isset($cloud_inventory[$imgVal->spu])){
                $cloud_inventory[$imgVal->spu] += $imgVal->cloud_num;
            }else{
                $cloud_inventory[$imgVal->spu] = $imgVal->cloud_num;
            }

        }

        //库存数据数组拼接spu=>库存
        $instock_inventory = [];//fba在仓库存
        $inbound_inventory = [];//fba在途库存
        $transfer_inventory = [];//fba预留库存
        $tongan_inventory = [];//同安仓库存
        $quanzhou_inventory = [];//泉州仓库存

        $product_detail = DB::table('product_detail')->whereIn('spu',$spu_arr)->where($where)->select('in_stock_num','in_bound_num','transfer_num','spu')->get()->toArray();
        foreach ($product_detail as $proVal){
            if(isset($instock_inventory[$proVal->spu])){
                $instock_inventory[$proVal->spu] += $proVal->in_stock_num;
            }else{
                $instock_inventory[$proVal->spu] = $proVal->in_stock_num;
            }

            if(isset($inbound_inventory[$proVal->spu])){
                $inbound_inventory[$proVal->spu] += $proVal->in_bound_num;
            }else{
                $inbound_inventory[$proVal->spu] = $proVal->in_bound_num;
            }

            if(isset($transfer_inventory[$proVal->spu])){
                $transfer_inventory[$proVal->spu] += $proVal->transfer_num;
            }else{
                $transfer_inventory[$proVal->spu] = $proVal->transfer_num;
            }
        }

        $saihe_inventory = DB::table('saihe_inventory')->whereIn('spu',$spu_arr)->whereIn('warehouse_id',[2,386,560])->select('good_num','spu','warehouse_id')->get()->toArray();

        foreach ($saihe_inventory as $saiheVal){
            if($saiheVal->warehouse_id==2||$saiheVal->warehouse_id==386){
                if(isset($tongan_inventory[$saiheVal->spu])){
                    $tongan_inventory[$saiheVal->spu] += $saiheVal->good_num;
                }else{
                    $tongan_inventory[$saiheVal->spu] = $saiheVal->good_num;
                }
            }
            if($saiheVal->warehouse_id==560) {
                if (isset($quanzhou_inventory[$saiheVal->spu])) {
                    $quanzhou_inventory[$saiheVal->spu] += $saiheVal->good_num;
                } else {
                    $quanzhou_inventory[$saiheVal->spu] = $saiheVal->good_num;
                }
            }
        }


        //计划补货数据数组拼接spu[运输方式]=>数量
        $plan_num = [];//计划数量
        $total_tongan_num = [];//同安计划中总数
        $total_quanzhou_num = [];//泉州计划中总数
        $total_cloud_num = [];//云仓计划中总数

        $amazon_buhuo_detail = DB::table('amazon_buhuo_detail as a')->leftJoin('amazon_buhuo_request as b','a.request_id','=','b.id')->whereIn('b.request_status',[4,5,6,7])->whereIn('a.spu',$spu_arr);
        if(isset($params['shop_id'])){
            $amazon_buhuo_detail =  $amazon_buhuo_detail->where('a.shop_id',$params['shop_id']);
        }
        $amazon_buhuo_detail =  $amazon_buhuo_detail->select('a.courier_num','a.shipping_num','a.air_num','a.spu','b.warehouse')->get()->toArray();

        foreach ($amazon_buhuo_detail as $detailVal){
            if(isset($plan_num[$detailVal->spu]['courier_num'])){
                $plan_num[$detailVal->spu]['courier_num'] += $detailVal->courier_num;
            }else{
                $plan_num[$detailVal->spu]['courier_num']= $detailVal->courier_num;
            }

            if(isset($plan_num[$detailVal->spu]['shipping_num'])){
                $plan_num[$detailVal->spu]['shipping_num'] += $detailVal->shipping_num;
            }else{
                $plan_num[$detailVal->spu]['shipping_num'] = $detailVal->shipping_num;
            }

            if(isset($plan_num[$detailVal->spu]['air_num'])){
                $plan_num[$detailVal->spu]['air_num'] += $detailVal->air_num;
            }else{
                $plan_num[$detailVal->spu]['air_num']= $detailVal->air_num;
            }

            $plan_total_num = $detailVal->air_num+$detailVal->courier_num+$detailVal->shipping_num;
            if($detailVal->warehouse ==1){
                //同安仓计划中总数
                if(isset($total_tongan_num[$detailVal->spu])){
                    $total_tongan_num[$detailVal->spu] += $plan_total_num;
                }else{
                    $total_tongan_num[$detailVal->spu]= $plan_total_num;
                }
            }elseif($detailVal->warehouse ==2){
                //泉州仓计划中总数
                if(isset($total_quanzhou_num[$detailVal->spu])){
                    $total_quanzhou_num[$detailVal->spu] += $plan_total_num;
                }else{
                    $total_quanzhou_num[$detailVal->spu]= $plan_total_num;
                }
            }elseif($detailVal->warehouse ==3){
                //云仓计划中总数
                if(isset($total_cloud_num[$detailVal->spu])){
                    $total_cloud_num[$detailVal->spu] += $plan_total_num;
                }else{
                    $total_cloud_num[$detailVal->spu]= $plan_total_num;
                }
            }
//            var_dump($total_tongan_num);

        }

        //订单数据拼接数组spu=>销量
        $orderlist= [];
        $order = Db::table('amazon_order_item')->whereIn('spu',$spu_arr)->where($where)->whereBetween('amazon_time',[$start_time, $end_time])->where('order_status','!=','Canceled')->select('quantity_ordered','spu')->get()->toArray();
        foreach ($order as $orderVal){
            if(isset($orderlist[$orderVal->spu])){
                $orderlist[$orderVal->spu] += $orderVal->quantity_ordered;
            }else{
                $orderlist[$orderVal->spu] = $orderVal->quantity_ordered;
            }
        }

        // var_dump($orderlist);
        // exit;

        //流量数据拼接数组spu=>浏览量
        $session_percentage = [];
        $percentage = Db::table('amazon_sale_percentage')->whereIn('spu',$spu_arr)->where($where)->whereBetween('ds', [$start_time, $end_time])->select('spu','session_percentage')->get()->toArray();
        foreach ($percentage as $sale){
            if(isset($session_percentage[$sale->spu])){
                $session_percentage[$sale->spu] += $sale->session_percentage;
            }else{
                $session_percentage[$sale->spu] = $sale->session_percentage;
            }
        }



        foreach ($spu as $key => $value) {
            if ($value->spu) {
                $thisSpu = $value->spu;
                //获取图片
                // if(isset($img_arr[$thisSpu])) {
                //     $spu[$key]->img = $img_arr[$thisSpu];
                // }else{
                //     $spu[$key]->img = '';
                // }
                //款式：1.爆款，2利润款，3清仓款
                // $sales_status = $value->sales_status;


                 //大类
                $spu[$key]->one_cate = '';
                $one_cate = $this->GetCategory($spu[$key]->one_cate_id);
                if($one_cate){
                    $spu[$key]->one_cate = $one_cate['name'];
                }

                //三类
                $spu[$key]->three_cate = '';
                $three_cate = $this->GetCategory($spu[$key]->three_cate_id);
                if($three_cate){
                    $spu[$key]->three_cate = $three_cate['name'];
                }


                $spu[$key]->cate_name = $spu[$key]->one_cate.$spu[$key]->three_cate;


                $year = date('Y');
                $month = date('m');
                $day = date('d', time());
                $last_month = date('m',strtotime("last month"));
                $lastDay = $this->get_lastday($year, $last_month);

                // if($sales_status == 1){
                //     //爆款  本周销量
                //     $startTime = date('Y-m-d 00:00:00', strtotime('-8 days',strtotime($year.'-'.$month.'-'.$day)));
                //     $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
                //     $quantity_ordered = Db::table('amazon_order_item')->where('spu',$thisSpu)->whereBetween('amazon_time',[$startTime, $endTime])->where('order_status','!=','Canceled')->sum('quantity_ordered');
                //     $s_day_quantity_ordered = round($quantity_ordered / 7, 2);
                // }elseif($sales_status == 1){
                //     //利润款 两周销量
                $startTime = date('Y-m-d 00:00:00', strtotime('-15 days',strtotime($year.'-'.$month.'-'.$day)));
                $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
                $quantity_ordered = Db::table('amazon_order_item')->where('spu',$thisSpu)->whereBetween('amazon_time',[$startTime, $endTime])->where($where)->where('order_status','!=','Canceled')->sum('quantity_ordered');
                $s_day_quantity_ordered = round($quantity_ordered / 14, 2);
                // }elseif($sales_status == 3){
                //     //清仓款 1月销量
                //     $startTime =date('Y-m-d 00:00:00', strtotime("-{$lastDay} days",strtotime($year.'-'.$month.'-'.$day)));
                //     $endTime = date('Y-m-d 00:00:00', strtotime('-1 days',strtotime($year.'-'.$month.'-'.$day)));
                //     $quantity_ordered = Db::table('amazon_order_item')->where('spu',$thisSpu)->whereBetween('amazon_time',[$startTime, $endTime])->where('order_status','!=','Canceled')->sum('quantity_ordered');
                //     $s_day_quantity_ordered = round($quantity_ordered /$lastDay, 2);
                // }


                //增长倍数
                $plan_multiple = $value->plan_multiple;



                $spu[$key]->img = $this->GetSpuImg($thisSpu);

                if(!empty($value->old_spu))  $value->spu = $value->old_spu;
                $inventoryParams['spu'] = $value->spu;
                //获取在仓库存
                if(isset($instock_inventory[$thisSpu])){
                    $spu[$key]->in_warehouse_inventory = $instock_inventory[$thisSpu];
                }else{
                    $spu[$key]->in_warehouse_inventory = 0;
                }
                //获取预留库存
                if(isset($transfer_inventory[$thisSpu])){
                    $spu[$key]->reserved_inventory = $transfer_inventory[$thisSpu];
                }else{
                    $spu[$key]->reserved_inventory = 0;
                }
                //获取在途库存
                if(isset($inbound_inventory[$thisSpu])){
                    $spu[$key]->in_road_inventory = $inbound_inventory[$thisSpu];
                }else{
                    $spu[$key]->in_road_inventory = 0;
                }
                //获取同安库存
                if(isset($tongan_inventory[$thisSpu])){
                    $spu[$key]->tongAn_inventory = $tongan_inventory[$thisSpu];
                    //获取预减后同安库存
                    if(isset($total_tongan_num[$thisSpu])){
                        $spu[$key]->tongAn_deduct_inventory = $spu[$key]->tongAn_inventory - $total_tongan_num[$thisSpu];
                    }else{
                        $spu[$key]->tongAn_deduct_inventory = $spu[$key]->tongAn_inventory;
                    }
                }else{
                    $spu[$key]->tongAn_inventory = 0;
                    $spu[$key]->tongAn_deduct_inventory = 0;
                }
                //获取泉州库存
                if(isset($quanzhou_inventory[$thisSpu])){
                    $spu[$key]->quanzhou_inventory = $quanzhou_inventory[$thisSpu];
                    //获取预减后泉州库存
                    if(isset($total_quanzhou_num[$thisSpu])){
                        $spu[$key]->quanzhou_deduct_inventory = $spu[$key]->quanzhou_inventory - $total_quanzhou_num[$thisSpu];
                    }else{
                        $spu[$key]->quanzhou_deduct_inventory = $spu[$key]->quanzhou_inventory;
                    }
                }else{
                    $spu[$key]->quanzhou_inventory = 0;
                    $spu[$key]->quanzhou_deduct_inventory = 0;
                }
                //获取云仓库存
                if(isset($cloud_inventory[$thisSpu])){
                    $spu[$key]->cloud_inventory = $cloud_inventory[$thisSpu];
                    //获取预减后云仓库存
                    if(isset($total_cloud_num[$thisSpu])){
                        $spu[$key]->cloud_deduct_inventory = $spu[$key]->cloud_inventory - $total_cloud_num[$thisSpu];
                    }else{
                        $spu[$key]->cloud_deduct_inventory = $spu[$key]->cloud_inventory;
                    }
                }else{
                    $spu[$key]->cloud_inventory = 0;
                    $spu[$key]->cloud_deduct_inventory = 0;
                }

                //获取虚拟库存
                $spu[$key]->factory_num = 0;
                $cuss = Db::table('self_custom_sku')->where('spu_id',$value->id)->get();

                foreach ($cuss as $cf) {
                    # code...
                    $spu[$key]->factory_num +=$cf->factory_num;
                }
                
                //获取快递发货
                if(isset($plan_num[$thisSpu]['courier_num'])){
                    $spu[$key]->courier_num = $plan_num[$thisSpu]['courier_num'];
                }else{
                    $spu[$key]->courier_num = '';
                }
                //获取海运发货
                if(isset($plan_num[$thisSpu]['shipping_num'])){
                    $spu[$key]->shipping_num = $plan_num[$thisSpu]['shipping_num'];
                }else{
                    $spu[$key]->shipping_num = '';
                }
                //获取空运发货
                if(isset($plan_num[$thisSpu]['air_num'])){
                    $spu[$key]->air_num = $plan_num[$thisSpu]['air_num'];
                }else{
                    $spu[$key]->air_num = '';
                }
                //获取销量
                if(isset($orderlist[$thisSpu])){
                    $spu[$key]->quantity_ordered = $orderlist[$thisSpu];
                }else{
                    $spu[$key]->quantity_ordered = 0;
                }

                //转化率
                if(isset($session_percentage[$thisSpu])){
                    $spu[$key]->conversion_rate = $session_percentage[$thisSpu]>0 ? round($spu[$key]->quantity_ordered / $session_percentage[$thisSpu], 4) * 100 : 0;
                }else{
                    $spu[$key]->conversion_rate = 0;
                }

//                $conversion_rate = 0;
//                $percentage_sql = "select sum(session_percentage) as session_percentage from amazon_sale_percentage where (spu = '{$value->spu}' or spu = '{$value->old_spu}') and ds between '{$start_time}' and '{$end_time}'";
//                $percentage = Db::select($percentage_sql);
//                $session_percentage = $percentage[0]->session_percentage ?? 0;
//                if ($session_percentage > 0 && $Datawhole['quantity_ordered'] > 0) {
//                    $quantity_ordered = $Datawhole['quantity_ordered'];
//                    $conversion_rate = round($quantity_ordered / $session_percentage, 4) * 100;
//                }
//                $spu[$key]->conversion_rate = (int)$conversion_rate;
                //退货数量，退货率
                if(isset($returnArr[$thisSpu])){
                    $spu[$key]->return_num = $returnArr[$thisSpu];
                    $spu[$key]->return_rate = $spu[$key]->quantity_ordered > 0 ? round($returnArr[$thisSpu] / $spu[$key]->quantity_ordered, 4) * 100 : 0;
                }else{
                    $spu[$key]->return_num = '';
                    $spu[$key]->return_rate = 0;
                }



                //生产数据
                $production = DB::table('cloudhouse_contract')->where('spu',$value->spu)->orWhere('spu',$value->old_spu)->select('count')->get();
                $nowspu = $value->spu;
                $nowold_spu = $value->old_spu;
                $outgoods = DB::table('goods_transfers_detail')
                    ->where('contract_no','!=','')
                    ->where(function ($query) use($nowspu,$nowold_spu){
                        $query->where('spu',$nowspu)->orWhere('spu',$nowold_spu);
                    })->sum('receive_num');

                if(!empty($production)){
                    $production = json_decode(json_encode($production),true);
                    $count = array_column($production,'count');
                    $spu[$key]->order_num = array_sum($count);
                }else{
                    $spu[$key]->order_num = 0;
                }
                if($outgoods){
                    $spu[$key]->shipment_num = $outgoods;
                }else{
                    $spu[$key]->shipment_num = 0;
                }

                if(  $spu[$key]->order_num-$spu[$key]->shipment_num >0){
                    $spu[$key]->no_shipment_num = $spu[$key]->order_num-$spu[$key]->shipment_num;
                }else{
                    $spu[$key]->no_shipment_num = 0;
                }

                // $spu[$key]->no_shipment_num  =  $spu[$key]->order_num-$spu[$key]->shipment_num >0? $spu[$key]->order_num-$spu[$key]->shipment_num : 0 ;


                //出入库时间
                //出
                //同安
                if(isset($params['shop_id'])){
                    $shop_id = $params['shop_id'];
                }
                if(isset($params['shop_id'])){
                    $outSql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and warehouse_id in(2,386) and type =1 and shop_id = {$shop_id} order by max desc limit 1 ";
                }else{
                    $outSql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and warehouse_id in(2,386) and type =1 order by max desc limit 1 ";
                }
              
                $outData1 = DB::select($outSql1);
                //泉州
                if(isset($params['shop_id'])){
                    $outSql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and warehouse_id=560 and type =1 and shop_id = {$shop_id} order by max desc limit 1 ";
                }else{
                    $outSql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and warehouse_id=560 and type =1 order by max desc limit 1 ";
                }
                 $outData2 = DB::select($outSql2);
                //万翔
  
                $outSql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where (spu='{$value->spu}' or spu='{$value->old_spu}') and type =1 order by max desc limit 1 ";
                

                $outData3 = DB::select($outSql3);
                //入
                //同安
                if(isset($params['shop_id'])){
                    $insql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and type =2 and shop_id = {$shop_id} order by max desc limit 1 ";
                }else{
                    $insql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (spu='{$value->spu}' or spu='{$value->old_spu}') and type =2 order by max desc limit 1 ";
                }

                $inData1 = DB::select($insql1);
                //泉州
                if(isset($params['shop_id'])){
                    $insql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where  (spu='{$value->spu}' or spu='{$value->old_spu}') and type =2 and shop_id = {$shop_id} order by max desc limit 1 ";
                }else{
                    $insql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where  (spu='{$value->spu}' or spu='{$value->old_spu}') and type =2 order by max desc limit 1 ";
                }

                $inData2 = DB::select($insql2);
                //万翔
   
                $insql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where (spu='{$value->spu}' or spu='{$value->old_spu}') and type =2 order by max desc limit 1 ";    
        
                $inData3 = DB::select($insql3);

                $spu[$key]->out1 = isset($outData1[0]) ? date('Y-m-d', strtotime($outData1[0]->operation_date)) : '';
                $spu[$key]->out2 = isset($outData2[0]) ? date('Y-m-d', strtotime($outData2[0]->operation_date)) : '';
                $spu[$key]->out3 = isset($outData3[0]) ? date('Y-m-d', strtotime($outData3[0]->createtime)) : '';
                $spu[$key]->in1 = isset($inData1[0]) ? date('Y-m-d', strtotime($inData1[0]->operation_date)) : '';
                $spu[$key]->in2 = isset($inData2[0]) ? date('Y-m-d', strtotime($inData2[0]->operation_date)) : '';
                $spu[$key]->in3 = isset($inData3[0]) ? date('Y-m-d', strtotime($inData3[0]->createtime)) : '';

                //日销
                $s_start_time = strtotime($start_time);
                $s_end_time = strtotime($end_time);
                $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
                $day_quantity_ordered = 0;
                if ($spu[$key]->quantity_ordered > 0) {
                    $day_quantity_ordered = round($spu[$key]->quantity_ordered / $day, 2);
                }

                $fba_inventory = $spu[$key]->in_warehouse_inventory + $spu[$key]->reserved_inventory + $spu[$key]->in_road_inventory;
                $here_inventory = $spu[$key]->tongAn_inventory + $spu[$key]->quanzhou_inventory + $spu[$key]->cloud_inventory;
                if ($day_quantity_ordered == 0) {
                    $spu[$key]->here_inventory_day = 999;
                    $spu[$key]->fba_inventory = 999;
                }

                if ($here_inventory == 0) {
                    $spu[$key]->here_inventory_day = 0;
                }
                if ($fba_inventory == 0) {
                    $spu[$key]->fba_inventory = 0;
                }

                if ($day_quantity_ordered > 0 && $here_inventory > 0) {
                    //本地仓库存周转天数=同安库存/日销
                    $spu[$key]->here_inventory_day = round($here_inventory / $day_quantity_ordered, 2);
                }
                if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
                    //fba库存周转天数=在仓+预留+在途/日销
                    $spu[$key]->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
                }

                //补货提醒 - 本地
                //1 需要下单  2 偏多  3 冗余
                $buhuo_status_bd = 0;
                
                $bdzz = $spu[$key]->here_inventory_day;
                if ($bdzz >= 0 && $bdzz < 60) {
                    $buhuo_status_bd = 1;
                }
                if ($bdzz >= 60 && $bdzz < 90) {
                    $buhuo_status_bd = 2;
                }
                if ($bdzz > 90) {
                    $buhuo_status_bd = 3;
                }

                $fbazz =   $spu[$key]->fba_inventory;
                //补货提醒-fba
                // $inventory_turnover = $this->inventoryTurnoverStatus($fba_inventory, $day_quantity_ordered, $plan_multiple);

                $buhuo_status_fba = 0; 
                //补货提醒更新
                if ($fbazz >= 0 && $fbazz < 60) {
                    $buhuo_status_fba = 1;
                }
                if ($fbazz >= 60 && $fbazz < 90) {
                    $buhuo_status_fba = 2;
                }
                if ($fbazz > 90) {
                    $buhuo_status_fba = 3;
                }

                $spu[$key]->buhuo_status_bd = $buhuo_status_bd; 
                $spu[$key]->buhuo_status_fba = $buhuo_status_fba; 

                //补货状态  1补货过多 近两周日销*60<计划补货数量
              
                // s_day_quantity_ordered
                $spu[$key]->send_status = 0;

                $courier_num  = 0;
                $shipping_num = 0;
                $air_num = 0;

                if(isset($spu[$key]->courier_num)){
                    $courier_num = (int)$spu[$key]->courier_num;
                }

                if(isset($spu[$key]->shipping_num)){
                    $shipping_num = (int)$spu[$key]->shipping_num;
                }
                if(isset($spu[$key]->air_num)){
                    $air_num = (int)$spu[$key]->air_num;
                }

                $jh_buhuo = $courier_num+$shipping_num+$air_num;
                //计划发货
                if($jh_buhuo>$s_day_quantity_ordered*60){
                    $spu[$key]->send_status = 1;
                }


                //下单状态  1下单过多 近两周日销*45<未出货数量
                $spu[$key]->place_order_status = 0;
                
                if($spu[$key]->no_shipment_num>$s_day_quantity_ordered*45){
                    $spu[$key]->place_order_status = 1;
                }

                

            

                 //补货建议合计:近1周日销*销售计划增长倍数（运营可调整）*60天-在途库存
                // $spu[$key]->buhuo_num = round($day_quantity_ordered*$plan_multiple*60 - $fba_inventory);
                // if($spu[$key]->buhuo_num <0){
                //     $spu[$key]->buhuo_num = 0;
                // }
                // //仓库数量<补货建议时需要下单 数量为 补货建议-仓库数量
                // if( $spu[$key]->buhuo_num>0 && $here_inventory< $spu[$key]->buhuo_num){
                //     $spu[$key]->place_order = $spu[$key]->buhuo_num - $here_inventory;
                //     // $spu[$key]->buhuo_status = 4;
                // }
                $msg = '近两周日销:'.$s_day_quantity_ordered.'未出货数量:'.$spu[$key]->no_shipment_num.'计划补货数量:'.$jh_buhuo.'下单状态:'.$spu[$key]->place_order_status.'补货状态:'.$spu[$key]->send_status.'补货提醒本地:'.$spu[$key]->buhuo_status_bd.'补货提醒fba:'.$spu[$key]->buhuo_status_fba;
                $spu[$key]->msg = $msg;

                
                $update['buhuo_status_bd'] =  $spu[$key]->buhuo_status_bd;
                $update['buhuo_status_fba'] =  $spu[$key]->buhuo_status_fba;
                $update['send_status'] =  $spu[$key]->send_status;
                $update['place_order_status'] =  $spu[$key]->place_order_status;
                Db::table('self_spu')->where('spu',$thisSpu)->update($update);
            }
        }


        if(!isset($params['spu'])&&!isset($params['one_cate_id'])&&!isset($params['two_cate_id'])&&!isset($params['three_cate_id'])){
            //不存在搜索条件时
            $redisdata['data'] =  $spu;
            $redisdata['total'] = $totalNum;
            Redis::setex('datawhole_spu:'.$params['start_time'].$params['end_time'].'page'.$page,3600*12,json_encode($redisdata));
        }

        $posttype = $params['posttype']??1;

        

        if($posttype==2){

            $p['title']='spu报表';
            $p['title_list']  = [
                'spu'=>'spu',
                'cate_name'=>'品类',
                'buhuo_status_bd'=>'补货提醒-本地',
                'buhuo_status_fba'=>'补货提醒-fba',
                'send_status'=>'补货状态',
                'place_order_status'=>'下单状态',
                'quantity_ordered'=>$params['start_time'].'-'.$params['end_time'].'销售',
                'conversion_rate'=>'转化率',
                'return_num'=>'退货数量',
                'return_rate'=>'退货率',
                'tongAn_inventory'=>'同安库存',
                'tongAn_deduct_inventory'=>'预减后同安仓库存',
                'quanzhou_inventory'=>'泉州仓库存',
                'quanzhou_deduct_inventory'=>'预减后泉州仓库存',
                'cloud_inventory'=>'云仓库存',
                'cloud_deduct_inventory'=>'预减后云仓库存',
                'in_warehouse_inventory'=>'fba在仓',
                'reserved_inventory'=>'fba预留',
                'in_road_inventory'=>'fba在途',
                'shipping_num'=>'计划海运',
                'air_num'=>'计划空运',
                'courier_num'=>'计划快递',
                'out1'=>'出仓时间-同安',
                'out2'=>'出仓时间-泉州',
                'out3'=>'出仓时间-云仓',
                'in1'=>'入仓时间-同安',
                'in2'=>'入仓时间-泉州',
                'in3'=>'入仓时间-云仓',
                'fba_inventory'=>'周转天数-fba',
                'here_inventory_day'=>'周转天数-本地',
                'order_num'=>'总下单',
                'shipment_num'=>'已出货',
                'no_shipment_num'=>'未出货',
            ];

            // $p['data'] = $spu;
            $p['data'] = json_decode(json_encode($spu),true);

            foreach ($p['data'] as $v) {
                //1 需要补货  2 库存偏多  3 库存冗余
                if($v['buhuo_status_bd']==1){
                    $v['buhuo_status_bd'] = '需要补货';
                }elseif($v['buhuo_status_bd']==2){
                    $v['buhuo_status_bd'] = '库存偏多';
                }elseif($v['buhuo_status_bd']==3){
                    $v['buhuo_status_bd'] = '库存冗余';
                }


                //1 需要补货  2 库存偏多  3 库存冗余
                if($v['buhuo_status_fba']==1){
                    $v['buhuo_status_fba'] = '需要补货';
                }elseif($v['buhuo_status_fba']==2){
                    $v['buhuo_status_fba'] = '库存偏多';
                }elseif($v['buhuo_status_fba']==3){
                    $v['buhuo_status_fba'] = '库存冗余';
                }


                if($v['send_status']==1){
                    $v['send_status'] = '过多';
                }else{
                    $v['send_status'] = '正常';
                }

                if($v['place_order_status']==1){
                    $v['place_order_status'] = '过多';
                }else{
                    $v['place_order_status'] = '正常';
                }


            }

            // var_dump($p);
            // exit;
            $this->excel_expord($p);
        }

        return [
            'data' => $spu,
            'totalnum' => $totalNum,
        ];
    }



    

    //获取上个月的最大日期
    public function get_lastday($year, $month)
    {
        if ($month == 2) {
            $lastday = 29;

        } elseif ($month == 4 || $month == 6 || $month == 9 || $month == 11) {
            $lastday = 30;

        } else {
            $lastday = 31;

        }
        return $lastday;
    }

    //计算补货指数
    public function inventoryTurnoverStatus($total_inventory, $week_daysales, $plan_multiple)
      {
  
          if ($total_inventory != 0 && $week_daysales == 0) {
              $inventory_turnover = 999;
          } elseif ($total_inventory == 0 && $week_daysales == 0) {
              $inventory_turnover = -1;
          } elseif ($total_inventory == 0 && $week_daysales != 0) {
              $inventory_turnover = 0;
          } else {
              $inventory_turnover = round($total_inventory / $week_daysales / $plan_multiple);
          }
  
          return $inventory_turnover;  //库存可周转天数
  
      }
  


    public function getDatawholeCustoms($params)
    {
        $spu = $this->GetNewSpu($params['spu']);

        $where['spu'] = $spu;
        $where['scs.status'] = 1;
        if (isset($params['custom_sku'])) {
            $where['custom_sku'] = $params['custom_sku'];
        }

        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $limitPage = $page * $limit;
        $pageNum = $page > 1 ? $page - 1 : 0;
        //查询self_custom_sku表custom_sku字段
        $customsQuery = Db::table('self_custom_sku as s')
            ->leftJoin('self_color_size as scs', 'scs.name', '=', 's.size')
            ->select('s.custom_sku', 'old_custom_sku')
            ->where($where)
            ->orderBy('s.spu', 'asc')
            ->orderBy('s.color', 'asc')
            ->orderBy('scs.sort', 'asc');
        //总条数
        $pageCount = $customsQuery->count();
        $customsSku = $customsQuery
            ->limit($limitPage)
            ->offset($pageNum)
            ->get()
            ->toArray();
        if (empty($customsSku)) {
            return [
                'data' => [],
                'totalnum' => 0,
            ];
        }
        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());

        $customsArr = array_column($customsSku, 'custom_sku');
        //根据custom_sku查询self_sku表
        $sku = Db::table('self_sku')->select('sku', 'old_sku', 'custom_sku')->whereIn('custom_sku', $customsArr)->get()->toArray();

        foreach ($customsSku as $key => $value) {
            $skuStr = '';
            foreach ($sku as $v) {
                if ($value->custom_sku == $v->custom_sku) {
                    $skuStr .= "'{$v->sku}',";
                    $skuStr .= "'{$v->old_sku}',";
                }
            }
            $customsSku[$key]->img = $this->GetCustomskuImg($value->custom_sku);//图片
            $customsSku[$key]->conversion_rate = 0;
            $customsSku[$key]->return_num = 0;
            $customsSku[$key]->return_rate = 0;
            $customsSku[$key]->tongAn_inventory = 0;
            $customsSku[$key]->tongAn_deduct_inventory = 0;
            $customsSku[$key]->in_warehouse_inventory = 0;
            $customsSku[$key]->reserved_inventory = 0;
            $customsSku[$key]->in_road_inventory = 0;
            $customsSku[$key]->quantity_ordered = 0;
            $customsSku[$key]->courier_num = 0;
            $customsSku[$key]->shipping_num = 0;
            $customsSku[$key]->air_num = 0;
            if (!empty($skuStr)) {

                $skuStr = rtrim($skuStr, ",");
                $inventoryParams['sku'] = $skuStr;
                $inventoryParams['param_style'] = 1;
                //获取库存
                $Inventory = $this->getInventoryByOther($inventoryParams);
                //获取发货与销量
                $Datawhole = $this->getDatawholeByOther($inventoryParams);
                // 库存
                $customsSku[$key]->tongAn_inventory = (int)$Inventory['tongAn_inventory'];
                $customsSku[$key]->quanZhou_inventory = (int)$Inventory['quanZhou_inventory'];
                $customsSku[$key]->cloud_inventory = (int)$value->cloud_num;
                // 预减后库存
                $customsSku[$key]->tongAn_deduct_inventory = (int)($Inventory['tongAn_inventory'] - $Datawhole['tongan_courier_num'] - $Datawhole['tongan_shipping_num'] - $Datawhole['tongan_air_num']) - $Datawhole['tongan_railway_num'] - $Datawhole['tongan_kahang_num'];
                $customsSku[$key]->quanZhou_deduct_inventory = (int)($Inventory['quanZhou_inventory'] - $Datawhole['quanzhou_courier_num'] - $Datawhole['quanzhou_shipping_num'] - $Datawhole['quanzhou_air_num']) - $Datawhole['quanzhourailway_num'] - $Datawhole['quanzhou_kahang_num'];
                $customsSku[$key]->cloud_deduct_inventory = (int)($value->cloud_num - $Datawhole['cloud_courier_num'] - $Datawhole['cloud_shipping_num'] - $Datawhole['cloud_air_num']) - $Datawhole['cloud_railway_num'] - $Datawhole['cloud_kahang_num'];
                // 在仓库内的数量
                $customsSku[$key]->in_warehouse_inventory = (int)$Inventory['in_warehouse_inventory'];
                $customsSku[$key]->reserved_inventory = (int)$Inventory['reserved_inventory'];
                $customsSku[$key]->in_road_inventory = (int)$Inventory['in_road_inventory'];
                $customsSku[$key]->quantity_ordered = $Datawhole['quantity_ordered'];
                $customsSku[$key]->courier_num = $Datawhole['courier_num'];
                $customsSku[$key]->shipping_num = $Datawhole['shipping_num'];
                $customsSku[$key]->air_num = $Datawhole['air_num'];
                //退货
                $skuArr = explode(',', $skuStr);
                $return = Db::table('amazon_return_order')
                    ->whereIn('sku', $skuArr)
                    ->whereBetween('beijing_date', [$start_time, $end_time])
                    ->count('quantity');
                $customsSku[$key]->return_num = $return;
                $customsSku[$key]->return_rate = $Datawhole['quantity_ordered'] > 0 ? round($return / $Datawhole['quantity_ordered'], 4) * 100 : 0;
            }

            //出入库时间
            //出
            //同安
            $outSql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (client_sku='{$value->custom_sku}' or client_sku='{$value->old_custom_sku}') and warehouse_id in(2,386) and type =1 order by max desc limit 1 ";
            $outData1 = DB::select($outSql1);
            //泉州
            $outSql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (client_sku='{$value->custom_sku}' or client_sku='{$value->old_custom_sku}') and warehouse_id=560 and type =1 order by max desc limit 1 ";
            $outData2 = DB::select($outSql2);
            //万翔
            $outSql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where (custom_sku='{$value->custom_sku}' or custom_sku='{$value->old_custom_sku}') and type =1 order by max desc limit 1 ";
            $outData3 = DB::select($outSql3);
            //入
            //同安
            $insql1 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where (client_sku='{$value->custom_sku}' or client_sku='{$value->old_custom_sku}') and type =2 order by max desc limit 1 ";
            $inData1 = DB::select($insql1);
            //泉州
            $insql2 = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where  (client_sku='{$value->custom_sku}' or client_sku='{$value->old_custom_sku}') and type =2 order by max desc limit 1 ";
            $inData2 = DB::select($insql2);
            //万翔
            $insql3 = "select createtime,UNIX_TIMESTAMP(createtime)as max from cloudhouse_record where (custom_sku='{$value->custom_sku}' or custom_sku='{$value->old_custom_sku}') and type =2 order by max desc limit 1 ";
            $inData3 = DB::select($insql3);

            $customsSku[$key]->out1 = isset($outData1[0]) ? date('Y-m-d', strtotime($outData1[0]->operation_date)) : '';
            $customsSku[$key]->out2 = isset($outData2[0]) ? date('Y-m-d', strtotime($outData2[0]->operation_date)) : '';
            $customsSku[$key]->out3 = isset($outData3[0]) ? date('Y-m-d', strtotime($outData3[0]->createtime)) : '';
            $customsSku[$key]->in1 = isset($inData1[0]) ? date('Y-m-d', strtotime($inData1[0]->operation_date)) : '';
            $customsSku[$key]->in2 = isset($inData2[0]) ? date('Y-m-d', strtotime($inData2[0]->operation_date)) : '';
            $customsSku[$key]->in3 = isset($inData3[0]) ? date('Y-m-d', strtotime($inData3[0]->createtime)) : '';


            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
            $day_quantity_ordered = 0;
            if ($Datawhole['quantity_ordered'] > 0) {
                $day_quantity_ordered = round($Datawhole['quantity_ordered'] / $day, 2);
            }

            $fba_inventory = $customsSku[$key]->in_warehouse_inventory + $customsSku[$key]->reserved_inventory + $customsSku[$key]->in_road_inventory;

            if ($day_quantity_ordered == 0) {
                $customsSku[$key]->tongAn_inventory_day = 999;
                $customsSku[$key]->fba_inventory = 999;
            }

            if ($customsSku[$key]->tongAn_inventory == 0) {
                $customsSku[$key]->tongAn_inventory_day = 0;
            }
            if ($fba_inventory == 0) {
                $customsSku[$key]->fba_inventory = 0;
            }

            if ($day_quantity_ordered > 0 && $customsSku[$key]->tongAn_inventory > 0) {
                //同安库存周转天数=同安库存/日销
                $customsSku[$key]->tongAn_inventory_day = round($customsSku[$key]->tongAn_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $customsSku[$key]->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
            }
            if(!empty($value->old_custom_sku)){
                $customsSku[$key]->custom_sku = $value->old_custom_sku;
            }
        }

        return [
            'data' => $customsSku,
            'totalnum' => $pageCount,
        ];
    }

    public function getDatawholeCustomsSku($params)
    {
        $customsSku = $this->GetNewCustomSku($params['custom_sku']);

        $where['ss.custom_sku'] = $customsSku;
        $where['scs.status'] = 1;
        if (isset($params['sku'])) {
            $where['ss.sku'] = $params['sku'];
        }

        if (isset($params['start_time'])) {
            $inventoryParams['start_time'] = $params['start_time'];
            $start = $params['start_time'] . ' 00:00:00';
        }
        if (isset($params['end_time'])) {
            $inventoryParams['end_time'] = $params['end_time'];
            $end = $params['end_time'] . ' 23:59:59';
        }
        $page = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $limitPage = $page * $limit;
        $pageNum = $page > 1 ? $page - 1 : 0;
        //查询self_custom_sku表custom_sku字段
        $skuQuery = Db::table('self_sku as ss')
            ->leftJoin('self_custom_sku as s', 's.custom_sku', '=', 'ss.custom_sku')
            ->leftJoin('self_color_size as scs', 'scs.name', '=', 's.size')
            ->select('ss.sku', 'ss.old_sku','s.custom_sku')
            ->where($where)
            ->orderBy('s.spu', 'asc')
            ->orderBy('s.color', 'asc')
            ->orderBy('scs.sort', 'asc');
        //总条数
        $pageCount = $skuQuery->count();
        $sku = $skuQuery
            ->limit($limitPage)
            ->offset($pageNum)
            ->get()
            ->toArray();
        if (empty($sku)) {
            return [
                'data' => [],
                'totalnum' => 0,
            ];
        }


        $start_time = isset($start) ? $start : date('Y-m-d 00:00:00', time());
        $end_time = isset($end) ? $end : date('Y-m-d 23:59:59', time());

        foreach ($sku as $key => $value) {
            $skuStr = "'{$value->sku}','{$value->old_sku}'";
            $sku[$key]->img = $this->GetCustomskuImg($value->custom_sku);//图片
            $sku[$key]->conversion_rate = 0;
            $sku[$key]->return_num = 0;
            $sku[$key]->return_rate = 0;
            $sku[$key]->tongAn_inventory = 0;
            $sku[$key]->tongAn_deduct_inventory = 0;
            $sku[$key]->in_warehouse_inventory = 0;
            $sku[$key]->reserved_inventory = 0;
            $sku[$key]->in_road_inventory = 0;
            $sku[$key]->quantity_ordered = 0;
            $sku[$key]->courier_num = 0;
            $sku[$key]->shipping_num = 0;
            $sku[$key]->air_num = 0;
            if (!empty($skuStr)) {
                $skuStr = rtrim($skuStr, ",");
                $inventoryParams['sku'] = $skuStr;
                $inventoryParams['param_style'] = 1;
                //获取库存
                $Inventory = $this->getInventoryByOther($inventoryParams);
                //获取发货与销量
                $Datawhole = $this->getDatawholeByOther($inventoryParams);

                $sku[$key]->tongAn_inventory = (int)$Inventory['tongAn_inventory'];
                $sku[$key]->tongAn_deduct_inventory = (int)($Inventory['tongAn_inventory'] - $Datawhole['courier_num'] - $Datawhole['shipping_num'] - $Datawhole['air_num']) - $Datawhole['railway_num'] - $Datawhole['kahang_num'];
                $sku[$key]->in_warehouse_inventory = (int)$Inventory['in_warehouse_inventory'];
                $sku[$key]->reserved_inventory = (int)$Inventory['reserved_inventory'];
                $sku[$key]->in_road_inventory = (int)$Inventory['in_road_inventory'];
                $sku[$key]->quantity_ordered = $Datawhole['quantity_ordered'];
                $sku[$key]->courier_num = $Datawhole['courier_num'];
                $sku[$key]->shipping_num = $Datawhole['shipping_num'];
                $sku[$key]->air_num = $Datawhole['air_num'];
                $sku[$key]->railway_num = $Datawhole['railway_num'];
                $sku[$key]->kahang_num = $Datawhole['kahang_num'];
                //退货
                $skuArr = explode(',', $skuStr);
                $return = Db::table('amazon_return_order')
                    ->whereIn('sku', $skuArr)
                    ->whereBetween('beijing_date', [$start_time, $end_time])
                    ->count('quantity');
                $sku[$key]->return_num = $return;
                $sku[$key]->return_rate = $Datawhole['quantity_ordered'] > 0 ? round($return / $Datawhole['quantity_ordered'], 4) * 100 : 0;

            }


            //出入库时间
            $outSql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where sku='{$value->sku}' or sku='{$value->old_sku}' and type =1 order by max desc limit 1 ";
            $outData = DB::select($outSql);
            //入
            $insql = "select operation_date,UNIX_TIMESTAMP(operation_date)as max from saihe_warehouse_log where sku='{$value->sku}' or sku='{$value->old_sku}' and type =2 order by max desc limit 1 ";
            $inData = DB::select($insql);

            $sku[$key]->out = isset($outData[0]) ? date('Y-m-d', strtotime($outData[0]->operation_date)) : '';
            $sku[$key]->in = isset($inData[0]) ? date('Y-m-d', strtotime($inData[0]->operation_date)) : '';

            //日销
            $s_start_time = strtotime($start_time);
            $s_end_time = strtotime($end_time);
            $day = ceil(($s_end_time - $s_start_time) / 86400) + 1;
            $day_quantity_ordered = 0;
            if ($Datawhole['quantity_ordered'] > 0) {
                $day_quantity_ordered = round($Datawhole['quantity_ordered'] / $day, 2);
            }

            $fba_inventory = $sku[$key]->in_warehouse_inventory + $sku[$key]->reserved_inventory + $sku[$key]->in_road_inventory;

            if ($day_quantity_ordered == 0) {
                $sku[$key]->tongAn_inventory_day = 999;
                $sku[$key]->fba_inventory = 999;
            }

            if ($sku[$key]->tongAn_inventory == 0) {
                $sku[$key]->tongAn_inventory_day = 0;
            }
            if ($fba_inventory == 0) {
                $sku[$key]->fba_inventory = 0;
            }

            if ($day_quantity_ordered > 0 && $sku[$key]->tongAn_inventory > 0) {
                //同安库存周转天数=同安库存/日销
                $sku[$key]->tongAn_inventory_day = round($sku[$key]->tongAn_inventory / $day_quantity_ordered, 2);
            }
            if ($day_quantity_ordered > 0 && $fba_inventory > 0) {
                //fba库存周转天数=在仓+预留+在途/日销
                $sku[$key]->fba_inventory = round($fba_inventory / $day_quantity_ordered, 2);
            }
            if(!empty($value->old_sku)){
                $sku[$key]->sku = $value->old_sku;
            }
        }


        return [
            'data' => $sku,
            'totalnum' => $pageCount,
        ];
    }


    public function addLinkrank($params)
    {
        $father_asin = $params['father_asin'];
        if (empty($father_asin)) {
            return [
                'code' => 'error',
                'msg' => '无father_asin'
            ];
        }

        $ranklist = Db::table('amazon_link_ranklist')->where('father_asin', $father_asin)->first();
        if ($ranklist) {
            return [
                'code' => 'error',
                'msg' => '父asin已存在'
            ];
        }

        if (!empty($params['shop_id'])) {
            $add['shop_id'] = $params['shop_id'];
            $addlist['shop_id'] = $params['shop_id'];
        }

        if (!empty($params['father_asin'])) {
            $add['father_asin'] = $params['father_asin'];
        }

        if (!empty($params['user_id'])) {
            $add['user_id'] = $params['user_id'];
            $addlist['user_id'] = $params['user_id'];
        }

        if (!empty($params['is_self'])) {
            $add['is_self'] = $params['is_self'];
        }

        if (!empty($params['sales_status'])) {
            $add['sales_status'] = $params['sales_status'];
            $addlist['sales_status'] = $params['sales_status'];
        }

        if (!empty($params['goods_style'])) {
            $add['goods_style'] = $params['goods_style'];
            $addlist['goods_style'] = $params['goods_style'];
        }

        if (!empty($params['gender'])) {
            $add['gender'] = $params['gender'];
            $addlist['gender'] = $params['gender'];
        }

        if (!empty($params['category_id'])) {
            $add['category_id'] = $params['category_id'];
            $addlist['category_id'] = $params['category_id'];
        }

        $skulist = Db::table('amazon_skulist')->where('father_asin', $father_asin)->first();
        if ($skulist) {
            Db::table('amazon_skulist')->where('father_asin', $father_asin)->update($addlist);
        }
        Redis::lpush('fnsku_list', json_encode($add));

        $add['time'] = time();
        $add['status'] = 1;

        $insert = Db::table('amazon_link_ranklist')->insert($add);
        if ($insert) {
            return [
                'code' => 'success',
                'data' => $add
            ];
        }
    }

    public function updateLinkrank($params)
    {
        $father_asin = $params['father_asin'];
        if (empty($father_asin)) {
            return [
                'code' => 'error',
                'msg' => '无father_asin'
            ];
        }

        $ranklist = Db::table('amazon_link_ranklist')->where('father_asin', $father_asin)->first();
        if (!$ranklist) {
            return [
                'code' => 'error',
                'msg' => '该父asin不存在'
            ];
        }

        if (!empty($params['shop_id'])) {
            $add['shop_id'] = $params['shop_id'];
            $addlist['shop_id'] = $params['shop_id'];
        }

        if (!empty($params['user_id'])) {
            $add['user_id'] = $params['user_id'];
            $addlist['user_id'] = $params['user_id'];
        }

        if (!empty($params['is_self'])) {
            $add['is_self'] = $params['is_self'];
        }

        if (!empty($params['sales_status'])) {
            $add['sales_status'] = $params['sales_status'];
            $addlist['sales_status'] = $params['sales_status'];
        }

        if (!empty($params['goods_style'])) {
            $add['goods_style'] = $params['goods_style'];
            $addlist['goods_style'] = $params['goods_style'];
        }

        if (!empty($params['gender'])) {
            $add['gender'] = $params['gender'];
            $addlist['gender'] = $params['gender'];
        }

        if (!empty($params['category_id'])) {
            $add['category_id'] = $params['category_id'];
            $addlist['category_id'] = $params['category_id'];
        }


        // Redis::lpush('fnsku_list', json_encode($add));

        $add['time'] = time();

        $update = Db::table('amazon_link_ranklist')->where('father_asin', $father_asin)->update($add);
        $skulist = Db::table('amazon_skulist')->where('father_asin', $father_asin)->update($addlist);
        if (!$update || !$skulist) {
            return [
                'code' => 'error',
                'msg' => '修改失败'
            ];
        }
        return [
            'code' => 'success',
            'data' => $add
        ];
    }


    //删除链接排名
    public function delLinkrank($params)
    {
        $id = $params['id'];
        $res = DB::table('amazon_link_ranklist')->whereIn('id',$id)->delete();
        if ($res) {
            return [
                'code' => 'success',
                'msg' => '删除成功'
            ];
        }
    }

    public function FnskuRankList($params)
    {

        //根据店铺

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $is_self = $params['is_self'] ?? 0;

        $where['a.is_self'] = $is_self;

        if (!empty($params['shop_id'])) {
            $where ['a.shop_id'] = $params['shop_id'];
        }

        if (!empty($params['father_asin'])) {
            $where ['a.father_asin'] = $params['father_asin'];
        }

        if (!empty($params['ds'])) {
            $whereb ['ds'] = $params['ds'];
        }


        if ($is_self == 0) {
            //根据运营
            if (!empty($params['user_id'])) {
                $where ['a.user_id'] = $params['user_id'];
            }
            $ranklist = Db::table('amazon_link_ranklist as a')->select('a.id','a.shop_id', 'a.user_id', 'a.sales_status', 'a.category_id', 's.shop_name', 'u.account', 'a.father_asin', 'c.product_typename as category', 'a.gender', 'a.sales_status', 'a.is_self', 'a.goods_style', 'cs.category_status as sales_statusname')->leftJoin('shop as s', 's.id', '=', 'a.shop_id')->leftJoin('amazon_category as c', 'c.id', '=', 'a.category_id')->leftJoin('users as u', 'u.id', '=', 'a.user_id')->leftJoin('amazon_category_status as cs', 'cs.id', '=', 'a.sales_status')->where($where)->where('status','!=',0);
        } else {
            $ranklist = Db::table('amazon_link_ranklist as a')->select('a.id','a.shop_id', 'a.category_id', 'a.father_asin')->where($where)->where('status','!=',0);
        }

        $totalNum =  $ranklist->count();

        $ranklist = $ranklist->offset($page)->limit($limit)->get();
        $time = time();
        $ds = date('Y-m-d', $time);
        $ds1 = date('Y-m-d', $time - 86400);
        $ds2 = date('Y-m-d', $time - 172800);
        foreach ($ranklist as $v) {
            # code...
            $res = $this->getNum($v->father_asin, $ds);
            $res1 = $this->getNum($v->father_asin, $ds1);
            $res2 = $this->getNum($v->father_asin, $ds2);
            $v->today_all_num = $res['all_num']>0?$res['all_num']:$res1['all_num'];
            $v->today_cate_num = $res['cate_num']>0?$res['cate_num']:$res1['cate_num'];
            $v->lastday_all_num = $res1['all_num'];
            $v->lastday_cate_num = $res1['cate_num'];
            $v->last2day_all_num = $res2['all_num'];
            $v->last2day_cate_num = $res2['cate_num'];
            // if($v->is_self==1){
            //     $v->is_self = '是';
            // }else{
            //     $v->is_self = '否';
            // }
        }


        $posttype = $params['posttype'];

        if($posttype==2){

            $p['title']='链接排名列表';
            $p['title_list']  = [
                // 'account'=>'运营',
                // 'category'=>'品类',
                'father_asin'=>'fasin',
                // 'gender'=>'性别',
                'today_all_num'=>$ds.'-总排名',
                'today_cate_num'=>$ds.'-分类排名',
                'lastday_all_num'=>$ds1.'-总排名',
                'lastday_cate_num'=>$ds1.'-分类排名',
                'last2day_all_num'=>$ds2.'-总排名',
                'last2day_cate_num'=>$ds2.'-分类排名',
            ];
            $p['data'] = $ranklist;
            $this->excel_expord($p);
            
        }


        return [
            'data' => $ranklist,
            'totalNum' => $totalNum,
            'today' => $ds,
            'lastday' => $ds1,
            "last2day" => $ds2
        ];

    }


    public function getNum($father_asin, $ds)
    {
        $where['father_asin'] = $father_asin;
        $where[] = ['ds', 'like', "%{$ds}%"];
        $num = Db::table('amazon_link_ranklog')->where($where)->first();
        $res['all_num'] = $num->all_num ?? 0;
        $res['cate_num'] = $num->cate_num ?? 0;
        return $res;
    }


    public function excelInsert($params)
    {
        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);

        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        //循环插入流量数据
        $a = 0;
        $b = 0;
        // $year = date('Y') - 1;
        for ($j = 2; $j <= $allRow; $j++) {
            $shop_name = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            $father_asin = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());

            $pattern4 = "/dp\/(.*)/";
            if (preg_match_all($pattern4, $father_asin, $matches)) {
                $father_asin = $matches[1][0];
            }


            $res = Db::table('amazon_link_ranklist')->where('father_asin', $father_asin)->first();
            if (!$res) {
                $add['father_asin'] = $father_asin;
                $add['is_self'] = 1;
                $add['shop_id'] = $shop_name;
                $insert = Db::table('amazon_link_ranklist')->insert($add);
            }


        }
        return [
            'type' => 'success',
            'msg' => '导入成功'
        ];

    }

    public function distributed_task($params)
    {
        //spu款号
        $data['spu'] = isset($params['spu']) ? $params['spu'] : null;
        //任务负责人
        $user_fz = isset($params['user_fz']) ? $params['user_fz'] : array();
        //任务创建人
        $data['user_cj'] = isset($params['user_cs']) ? $params['user_cs'] : 0;
        //任务分类
        $data['class_id'] = isset($params['class_id']) ? $params['class_id'] : 0;
        //备注说明
        $data['desc'] = isset($params['desc']) ? $params['desc'] : '';
        //执行天数
        $data['day_yj'] = isset($params['day_yj']) ? $params['day_yj'] : 7;
        //任务分类名
        $class_name = DB::table('task_class')->where('id', $data['class_id'])->select('title')->first();
        if (empty($class_name)) return ['type' => 'fail', 'msg' => '任务派发失败，没有找到该任务分类'];
        $call_task = new \App\Libs\wrapper\Task();
        $fz_name = DB::table('users')->whereIn('Id', $user_fz)->select('Id', 'account')->get();
        $fz_name = json_decode(json_encode($fz_name), true);
        if (!empty($data['spu'])) {
            if (is_array($data['spu'])) {
                $desc = implode(',', $data['spu']);
                $data['desc'] = $desc . ' : ' . $data['desc'];
                if (!is_null($user_fz)) {
                    $access = '';
                    $fail = '';
                    foreach ($fz_name as $fzren) {
                        $data['user_fz'] = $fzren['Id'];
                        $data['name'] = $class_name->title . '-' . $fzren['account'] . time();
                        $data['audit_method'] = 2;//审核方式为单人审核通过
                        $data['ext'] = array('tasks_text' => '待执行任务', 'tasks_img' => '', 'tasks_file' => '');
                        $data['node'][0] = array(
                            'name' => '执行' . $class_name->title . '任务',
                            'circulation' => 2
                        );
                        $data['node'][0]['node_task_data'][0] =
                            array(
                                'task' => '实时反馈进度，填写进度说明',
                                'user_id' => $fzren['Id'],
                                'day_yj' => $data['day_yj'],
                            );
                        $task_add = $call_task->task_add($data);
                        if ($task_add) {
                            if (!stripos($access, $fzren['account'])) $access .= $fzren['account'] . ',';
                        } else {
                            if (!stripos($fail, $fzren['account'])) $fail .= $fzren['account'] . ',';
                        }
                    }
                } else {
                    return ['type' => 'fail', 'msg' => '任务派发失败，请选择任务执行人'];
                }
            } else {
                $data['desc'] = $data['spu'] . ' : ' . $data['desc'];
                if (!is_null($user_fz)) {
                    $access = '';
                    $fail = '';
                    foreach ($fz_name as $fzren) {
                        $data ['user_fz'] = $fzren['Id'];
                        $data['name'] = $class_name->title . '-' . $fzren['account'] . time();
                        $data['audit_method'] = 2;//审核方式为单人审核通过
                        $data['ext'] = array('tasks_text' => '待执行任务', 'tasks_img' => '', 'tasks_file' => '');
                        $data['node'][0] = array(
                            'name' => '执行' . $class_name->title . '任务',
                            'circulation' => 2
                        );
                        $data['node'][0]['node_task_data'][0] =
                            array(
                                'task' => '实时反馈进度，填写进度说明',
                                'user_id' => $fzren['Id'],
                                'day_yj' => $data['day_yj'],
                            );
                        $task_add = $call_task->task_add($data);
                        if ($task_add) {
                            $access .= $fzren['account'] . ',';
                        } else {
                            $fail .= $fzren['account'] . ',';
                        }
                    }
                } else {
                    return ['type' => 'fail', 'msg' => '任务派发失败，请选择任务执行人'];
                }
            }
        }

        $msg = '';
        if ($access != '') $msg .= $access . '任务派发成功';
        if ($fail != '') $msg .= PHP_EOL . $fail . '任务派发失败';
        if ($access != '' || $fail != '') {
            return ['type' => 'success', 'msg' => $msg];
        } else {
            return ['type' => 'fail', 'msg' => '任务派发失败，未知错误'];
        }


    }


    //生产下单导入
    public function PlaceOrderImport($params)
    {

        ////获取Excel文件数据
        $is_new = $params['is_new'] ?? 1;
        $file = $params['file'];
        $user_id = $params['user_id'];
        $supply_time = $params['supply_time'];
        $task_id = $params['task_id'];
        $supply_time = strtotime($supply_time);
        //获取文件后缀名

        // $extension = $file->getClientOriginalExtension();


        // if ($extension == 'csv') {
        //     $PHPExcel = new \PHPExcel_Reader_CSV();
        // } elseif ($extension == 'xlsx') {
        //     $PHPExcel = new \PHPExcel_Reader_Excel2007();
        // } else {
        //     $PHPExcel = new \PHPExcel_Reader_Excel5();
        // }

        // if (!$PHPExcel->canRead($file)) {
        //     return [
        //         'type' => 'fail',
        //         'msg' => '导入失败，Excel文件错误'
        //     ];
        // }
        if(!file_exists($file)){
            return [
                        'type' => 'fail',
                        'msg' => '无此文件，当前路径'.dirname(__FILE__)
                    ];
            
        }

        $PHPExcel = new \PHPExcel_Reader_Excel2007();

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $time = time();

        // $product_user_id = '';
        // $operate_user_id = '';
        // $supply_user_id = '';
        // $product_user = trim($Sheet->getCellByColumnAndRow(1, 4)->getValue());
        // if (!empty($product_user)) {
        //     $product_user_res = Db::table('users')->where('account', $product_user)->first();
        //     if (!$product_user_res) {
        //         return ['type' => 'fail', 'msg' => '产品负责人信息有误,文件:'.$file];
        //     }
        //     $product_user_id = $product_user_res->Id;
        // }

        // $operate_user = trim($Sheet->getCellByColumnAndRow(1, 5)->getValue());
        // if (!empty($operate_user)) {
        //     $operate_user_res = Db::table('users')->where('account', $operate_user)->first();
        //     if (!$operate_user_res) {
        //         return ['type' => 'fail', 'msg' => '运营负责人信息有误,文件:'.$file];
        //     }
        //     $operate_user_id = $operate_user_res->Id;
        // }
        // $supply_user = trim($Sheet->getCellByColumnAndRow(1, 6)->getValue());
        // if (!empty($supply_user)) {
        //     $supply_user_res = Db::table('users')->where('account', $supply_user)->first();
        //     if (!$supply_user_res) {
        //         return ['type' => 'fail', 'msg' => '供应链负责人信息有误,文件:'.$file];
        //     }
        //     $supply_user_id = $supply_user_res->Id;
        // }


        for ($j = 8; $j <= $allRow; $j++) {
            //款号
            $spu = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if (!empty($spu)) {
                $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
                if (!$res) {
                    return ['type' => 'fail', 'msg' => '该spu不存在，请先生成' . $spu.'--文件:'.$file];
                }
                $add_list[$j - 3]['spu'] = $spu;
                //英文名
                $add_list[$j - 3]['name_en'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                //颜色名
                $add_list[$j - 3]['color_name'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                // //色号
                // $add_list[$j - 3]['color_num'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                //颜色英文名
                $add_list[$j - 3]['color_name_en'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                //总数量
                $add_list[$j - 3]['order'] = trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
                //尺码

                 //XS
                $add_list[$j - 3]['XS'] = $Sheet->getCellByColumnAndRow(6, $j)->getValue() ?? 0;
                //s
                $add_list[$j - 3]['S'] = $Sheet->getCellByColumnAndRow(7, $j)->getValue() ?? 0;
                //M
                $add_list[$j - 3]['M'] = $Sheet->getCellByColumnAndRow(8, $j)->getValue() ?? 0;
                //L
                $add_list[$j - 3]['L'] = $Sheet->getCellByColumnAndRow(9, $j)->getValue() ?? 0;
                //XL
                $add_list[$j - 3]['XL'] = $Sheet->getCellByColumnAndRow(10, $j)->getValue() ?? 0;
                //2XL
                $add_list[$j - 3]['2XL'] = $Sheet->getCellByColumnAndRow(11, $j)->getValue() ?? 0;
                //3XL
                $add_list[$j - 3]['3XL'] = $Sheet->getCellByColumnAndRow(12, $j)->getValue() ?? 0;
                //4XL
                $add_list[$j - 3]['4XL'] = $Sheet->getCellByColumnAndRow(13, $j)->getValue() ?? 0;
                //5XL
                $add_list[$j - 3]['5XL'] = $Sheet->getCellByColumnAndRow(14, $j)->getValue() ?? 0;


            }
        }
        
        foreach ($add_list as $value) {

            $query['spu'] = $value['spu'];

            // //修改运营负责人和供应链负责人
            // $spu_insert['operate_user_id'] = $operate_user_id;
            // $spu_insert['supply_user_id'] = $supply_user_id;
            // Db::table('amazon_place_order')->where($query)->update($spu_insert);


            $query['color_name_en'] = $value['color_name_en'];
            $query['order'] = $value['order'];
            $query['supply_time'] = $supply_time;
            $query['task_id'] = $task_id;
            $is_repeat = Db::table('amazon_place_order')->where($query)->first();
            if (!$is_repeat) {
                $value['supply_time'] = $supply_time;
                // $value['product_user_id'] = $product_user_id;
                // $value['operate_user_id'] = $operate_user_id;
                // $value['supply_user_id'] = $supply_user_id;
                $value['create_time'] = $time;
                $value['is_new'] = $is_new;
                $value['create_user'] = $user_id;

                //判断是否存在颜色名
                $colorres = Db::table('self_color_size')->where('english_name', $value['color_name_en'])->first();
                if ($colorres) {
                    $color_id = $colorres->id;
                } else {
                    return [
                            'type' => 'fail',
                            'msg' => '该颜色暂未录入-'.$value['color_name_en']
                        ];
                    // //如果没有颜色标识，则手动生成,并存入表
                    // if (empty($value['color_identifying'])) {
                    //     try {
                    //         //code...
                    //         $value['color_identifying'] = $this->GetIdentifying($value['color_name_en']);
                    //         //去空格
                    //         $value['color_identifying'] = str_replace(' ','',$value['color_identifying']);

                    //         //去掉回车
                    //         $value['color_identifying'] = str_replace(array("\r\n", "\r", "\n"), "", $value['color_identifying']);
                    //         if(strlen($value['color_identifying'])!=3){
                    //             return [
                    //                 'type' => 'fail',
                    //                 'msg' => '颜色标识生成错误，请检查是否存在额外空格与回车'.$value['color_name_en'].'文件:'.$file
                    //             ];
                    //         }
                    //     } catch (\Throwable $th) {
                    //         //throw $th;
                    //         return [
                    //             'type' => 'fail',
                    //             'msg' => '颜色标识生成错误，请修改后重试'.$value['color_name_en'].'文件:'.$file
                    //         ];
                    //     }
                        
                    // }
                    // $colorinsert['status'] = 1;
                    // $colorinsert['name'] = $value['color_name'];
                    // $colorinsert['english_name'] = $value['color_name_en'];
                    // $colorinsert['identifying'] = $value['color_identifying'];
                    // $colorinsert['type'] = 1;
                    // $colorinsert['create_time'] = $time;
                    // $colorinsert['user_id'] = $user_id;
                    // $color_id = Db::table('self_color_size')->insertGetId($colorinsert);
                }

                $spucolorinsert['spu'] = $value['spu'];
                $spucolorinsert['color_id'] = $color_id;
                $spucolorinsert['status'] = 1;
                $isrepeat = Db::table('self_spu_color')->where($spucolorinsert)->first();
                if(!$isrepeat){
                    Db::table('self_spu_color')->insert($spucolorinsert);
                }
                $value['status'] = 0;//待审核
                $value['task_id'] = $task_id;//任务id
                $placeres = Db::table('amazon_place_order')->insert($value);

                if (!$placeres) {
                    return ['type' => 'fail', 'msg' => '导入失败,文件:'.$file];
                }
            }
        }

        return ['type' => 'success', 'msg' => '导入成功'];
    }


    //生产下单导入-新
    public function PlaceOrderImportNew($params)
    {

        ////获取Excel文件数据
       //  $is_new = $params['is_new'] ?? 1;
        $file = $params['file'];
       //  $user_id = $params['user_id'];
       //  $supply_time = $params['supply_time'];
       //  $task_id = $params['task_id'];
       //  $supply_time = strtotime($supply_time);
        //获取文件后缀名
        if(!file_exists($file)){
            return [
                        'type' => 'fail',
                        'msg' => '无此文件，当前路径'.dirname(__FILE__)
                    ];
            
        }

        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }


       //  $PHPExcel = new \PHPExcel_Reader_Excel2007();

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $time = time();

        $start = 2;
        $end = 4;

        for ($i = 0; $i <= $allRow; $i++) {
           $name =  trim($Sheet->getCellByColumnAndRow($i,1)->getValue());
        //    echo $name;
            if($name=='总数量'){
             $end = $i;
            }
        }

        $list=[];

        for ($j = 2; $j <= $allRow; $j++) {
            //库存sku
            $custom_sku = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if (!empty($custom_sku)) {
                $res = Db::table('self_custom_sku')->where('custom_sku', $custom_sku)->orwhere('old_custom_sku', $custom_sku)->first();
                if (!$res) {
                    return ['type' => 'fail', 'msg' => '该库存sku不存在，请先生成' . $custom_sku.'--文件:'.$file];
                }

            $list[$j-2]['custom_sku'] = $custom_sku;
            $list[$j-2]['name_en'] =trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
        
            for ($i=2; $i < $end; $i++) { 
                # code...
                $list[$j-2]['num'][$i-2] = (int)$add_list[$j-2]['name_en'] = trim($Sheet->getCellByColumnAndRow($i, $j)->getValue());
            }
            // $list[$j-2]['num'] = trim($Sheet->getCellByColumnAndRow($end, $j)->getValue());

            $spus = Db::table('self_spu as a')
                ->leftJoin('self_base_spu as b','a.base_spu_id','=','b.id')
                ->leftjoin('self_spu_info as spi','b.id','=','spi.base_spu_id')
                ->where('a.id',$res->spu_id)->select('a.*','b.class','spi.unit_price')->first();
            if(!$spus){
                return ['type' => 'fail', 'msg' => '该spu不存在' . $res->spu]; 
            }else{
                if($spus->class==1&&$spus->type==1){
                    if(isset($cateArr)){
                        if($cateArr!=$spus->one_cate_id.$spus->two_cate_id.$spus->three_cate_id){
                            return ['type' => 'fail', 'msg' => '自主研发款只能同品类下单'.$spus->spu];
                        }
                    }else{
                        $cateArr = $spus->one_cate_id.$spus->two_cate_id.$spus->three_cate_id;
                    }
                }
                $list[$j-2]['spu'] = $spus->spu;
                if($spus->old_spu){
                    $list[$j-2]['spu'] = $spus->old_spu;
                }
            }

            $list[$j-2]['color'] = '';
            if ($res->type == 1) {
                $color = Db::table('self_color_size')->where('identifying',$res->color)->first();
                if(!$color){
                    return ['type' => 'fail', 'msg' => '该库存sku颜色异常' . $custom_sku];
                }
                $list[$j-2]['color'] = $color->english_name;
            }

            $list[$j-2]['size'] = $res->size;

            $list[$j-2]['unit_price'] = $spus->unit_price;
            $list[$j-2]['class'] = $spus->class;
            }
        }



        return ['type' => 'success', 'data'=> $list, 'msg' => '导入成功'];
    }



     //生产下单导入-新
     public function PlaceOrderImportNewB($params)
     {
 
         ////获取Excel文件数据
        //  $is_new = $params['is_new'] ?? 1;
         $file = $params['file'];
        //  $user_id = $params['user_id'];
        //  $supply_time = $params['supply_time'];
        //  $task_id = $params['task_id'];
        //  $supply_time = strtotime($supply_time);
         //获取文件后缀名
         if(!file_exists($file)){
             return [
                         'type' => 'fail',
                         'msg' => '无此文件，当前路径'.dirname(__FILE__)
                     ];
             
         }

         $extension = $file->getClientOriginalExtension();
         if ($extension == 'csv') {
             $PHPExcel = new \PHPExcel_Reader_CSV();
         } elseif ($extension == 'xlsx') {
             $PHPExcel = new \PHPExcel_Reader_Excel2007();
         } else {
             $PHPExcel = new \PHPExcel_Reader_Excel5();
         }
 
 
        //  $PHPExcel = new \PHPExcel_Reader_Excel2007();
 
         $PHPExcelLoad = $PHPExcel->load($file);
         $Sheet = $PHPExcelLoad->getSheet(0);
         $add_list = array();
         /**取得一共有多少行*/
         $allRow = $Sheet->getHighestRow();
         $time = time();
 
         for ($j = 8; $j <= $allRow; $j++) {
             //款号
             $spu = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
             if (!empty($spu)) {
                 $res = Db::table('self_spu')->where('spu', $spu)->orwhere('old_spu', $spu)->first();
                 if (!$res) {
                     return ['type' => 'fail', 'msg' => '该spu不存在，请先生成' . $spu.'--文件:'.$file];
                 }
                 $add_list[$j - 3]['spu'] = $spu;
                 //英文名
                 $add_list[$j - 3]['name_en'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                 //颜色名
                 $add_list[$j - 3]['color_name'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                 // //色号
                 // $add_list[$j - 3]['color_num'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                 //颜色英文名
                 $add_list[$j - 3]['color_name_en'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                 //总数量
                 $add_list[$j - 3]['order'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                 //尺码
 
                  //XS
                 $add_list[$j - 3]['size']['XS'] = $Sheet->getCellByColumnAndRow(5, $j)->getValue() ?? 0;
                 //s
                 $add_list[$j - 3]['size']['S'] = $Sheet->getCellByColumnAndRow(6, $j)->getValue() ?? 0;
                 //M
                 $add_list[$j - 3]['size']['M'] = $Sheet->getCellByColumnAndRow(7, $j)->getValue() ?? 0;
                 //L
                 $add_list[$j - 3]['size']['L'] = $Sheet->getCellByColumnAndRow(8, $j)->getValue() ?? 0;
                 //XL
                 $add_list[$j - 3]['size']['XL'] = $Sheet->getCellByColumnAndRow(9, $j)->getValue() ?? 0;
                 //2XL
                 $add_list[$j - 3]['size']['2XL'] = $Sheet->getCellByColumnAndRow(10, $j)->getValue() ?? 0;
                 //3XL
                 $add_list[$j - 3]['size']['3XL'] = $Sheet->getCellByColumnAndRow(11, $j)->getValue() ?? 0;
                 //4XL
                 $add_list[$j - 3]['size']['4XL'] = $Sheet->getCellByColumnAndRow(12, $j)->getValue() ?? 0;
                 //5XL
                 $add_list[$j - 3]['size']['5XL'] = $Sheet->getCellByColumnAndRow(13, $j)->getValue() ?? 0;
 
 
             }
         }
         
        //  var_dump($add_list);
        //  exit;
         $datas=[];
         $i = 0;
         foreach ($add_list as $value) {
 
             $spu = $value['spu'];
             $color_name_en = $value['color_name_en'];
             $colorres = Db::table('self_color_size')->where('english_name', $color_name_en)->first();
             if (!$colorres) {
                return [
                    'type' => 'fail',
                    'msg' => '该颜色暂未录入-'.$color_name_en
                ];
             }
             $sizes =  $value['size'];

             $onedata = [];

             foreach ($sizes as $size => $num) {
                # code...
                if($num>0){
                    $spu = $this->GetNewSpu($spu);
                    $cus = Db::table('self_custom_sku')->where('spu',$spu)->where('color',$colorres->identifying)->where('size',$size)->first();
                    if(!$cus){
                        return [
                            'type' => 'fail',
                            'msg' => '无此库存sku---spu:'.$spu.'--color:'.$color_name_en.'--size:'.$size
                        ];
                    }
                    $onedata['spu'] = $spu;
                    $onedata['color'] = $color_name_en;
                    $onedata['size'] = $size;
                    $onedata['num'] = $num;
                    $onedata['name_en'] = $value['name_en'];
                    $onedata['custom_sku'] = $cus->custom_sku;
                    
                    $datas[$i] = $onedata;
                    $i++;
                }
             }


         }

        //  $this->PlaceOrderTask($datas);
 
         return ['type' => 'success', 'data'=> $datas, 'msg' => '导入成功'];
     }

     //新增备面料下单
//     public function Sparefabric($params){
//
//         $task = DB::table('amazon_place_order_task')->select('id','creattime')->orderBy('creattime','desc')->first();
//         $expire_time = date($task->creattime,strtotime("+7 days"));
//
//         //下单时间
//         $creattime = date('Y-m-d H:i:s',time());
//         if($creattime<$task->creattime){
//             return [
//                 'type' => 'fail',
//                 'msg' => '当前有备面料计划还在进行中，无法新增'
//             ];
//         }
//         //供应链负责人
//         $supply_user = '';
//         if(isset($params['supply_user'])){
//             $supply_user = implode(',',$params['supply_user']);
//         }
//         $expect_date = json_encode($params['expect_date']);
//
//         $addtask['user_id'] = 0;
//         $addtask['creattime'] = $creattime;
//         $addtask['status'] = 0;
//         $addtask['sku_count'] = 0;
//         $addtask['order_num'] = 0;
//         $addtask['type'] = 1;
//
//         $addtask['expect_date'] = $expect_date;
//         $addtask['supply_user'] = $supply_user;
//
//         $task = DB::table('amazon_place_order_task')->insert($addtask);
//         if($task){
//             return [
//                 'type' => 'success',
//                 'msg' => '新增成功'
//             ];
//         }else{
//             return [
//                 'type' => 'fail',
//                 'msg' => '新增失败'
//             ];
//         }
//     }

    //生产下单任务
    public function PlaceOrderTask($params){
        $day = date("l");
        // if($day=='Tuesday'||$day=='Monday'){
        //     return [
        //         'type' => 'fail',
        //         'msg' => '非下单日!无法下单!请在周三，周四，周五，周六，周日提交下单!'
        //     ];
        // }

        //自主研发  线上采购
        //正常采购任务模版
        $task_class_id = 19;
        //平台  0其他  1亚马逊
        $platform = $params['platform']??0;

        if($platform==1){
            //亚马逊下单 fasin预算下单
            $day = date("d");
            if($day<15||$day>20){
                return [
                            'type' => 'fail',
                            'msg' => '非下单日!无法下单!请在每月的15-20号之间下单!'
                        ];
            }

            $custom_sku_list =  $params['custom_sku_list'];
            $fasin_code =  $custom_sku_list[0]['fasin_code'];
            $order_num = 0;
            foreach ($custom_sku_list as $cs) {
                $order_num += array_sum($cs['num']);
            }

            $order_time = date('Y-m',time());

            $have_order_num = $this->getFasinOrderPlace($fasin_code,$order_time);

            $order_total = $have_order_num['total']+$order_num;

            $plantime = date('m',time());

            $year = date('Y',time());

            if($plantime==4||$plantime==5||$plantime==6||$plantime==7||$plantime==8||$plantime==9){
                return['type'=>'fail','msg'=>'非下单月，预算下单仅可在1,2,3,10,11,12月下'];
            }

            if($plantime==10){ $year = date('Y',strtotime('+1 year')); $plantime1 = 1;$plantime2 =2;}
            if($plantime==11){ $year = date('Y',strtotime('+1 year')); $plantime1 = 3;$plantime2 =4;}
            if($plantime==12){ $year = date('Y',strtotime('+1 year')); $plantime1 = 5;$plantime2 =6;}
            if($plantime==1){$plantime1 = 7;$plantime2 =8;}
            if($plantime==2){$plantime1 = 9;$plantime2 =10;}
            if($plantime==3){$plantime1 = 11;$plantime2 =12;}


            $plan_moon1 = 'month_sales'.$plantime1; //下一个月月销
            $plan_moon2 = 'month_sales'.$plantime2; //后一个月月销

            $plans = db::table('amazon_fasin_plan_info')->where('fasin_code', $fasin_code)->where('year',$year)->first();
            $plan_num1 = $plans-> $plan_moon1;
            $plan_num2 = $plans-> $plan_moon2;
            $plan_num = $plan_num1+$plan_num2;
            if($plan_num<$order_total){
                return [
                    'type' => 'fail',
                    'msg' => '下单数已超出预算数,无法下单！本次下单:'.$order_num.'，已下单:'. $have_order_num['total'].','.$plantime1.','.$plantime2.'月预算：'.$plan_num
                ];
            }


            return['type'=>'fail','msg'=>'下单成功,本次下单:'.$order_num.'，已下单:'. $have_order_num['total'].','.$plantime1.','.$plantime2.'月预算：'.$plan_num];

        }
        //下单人
        $user_id = $params['user_id'];
        //下单时间
        $creattime = date('Y-m-d H:i:s',time());
        //下单状态 0.未发布任务1.已发布任务，待审核2.已审核，待录入艾诺科3.已录入艾诺科
        $status = 0;

        $content = $params['content']??'';
        //类型1.新品下单 2.旧品翻单
        $type = $params['type']??1;
//        //模式1.集体下单 2.个人下单
//        $mode = $params['mode']??0;

        $content = $params['content']??'';

        //销售市场1.美国 2.欧洲 3.日本
        $sales_market = $params['sales_market'];
        //销售人群1.成年男性 2.成年女性 3.中大童 4.幼童
        $sale_crowd = $params['sale_crowd'];
        //是否优化尺寸 1.是 2.否
        $is_optimization = $params['is_optimization'];
        // 平台
        $platformId = $params['platform_id'] ?? 0;
        if ($type == 2){
            $shop = db::table('shop')->where('id', $params['shop_id'])->first();
            $platformId = $shop->platform_id ?? 0;
        }
        if (empty($platformId)){
            return [
                'type' => 'fail',
                'msg' =>  '未给定平台标识或店铺未绑定平台！'
            ];
        }
        //供应链负责人
        $supply_user = '';
        if(isset($params['supply_user'])){
            $supply_user = implode(',',$params['supply_user']);
        }
        //吊牌
        $tag = $params['tag'];
        //分几批期望交期
        $batch = count($params['expect_date']);

        $expect_date = json_encode($params['expect_date']);

        //店铺
        $shop_id = $params['shop_id']??0;

        $spu_self_type = 0;

        if(isset($params['custom_sku_list'])){

            // if (count($params['custom_sku_list']) != count(array_unique($params['custom_sku_list']))) {
            //     return [
            //         'type' => 'fail',
            //         'msg' =>  '存在重复库存sku数据，请重新检查删除重复数据'
            //     ];
            // }

            $custom_sku_list =  $params['custom_sku_list'];

            $errcs = [];
            $is_repeats = [];

            $spunum = [];
            if (!isset($params['self_type']) || !in_array($params['self_type'], [1, 2])){
                return [
                    'type' => 'fail',
                    'msg' => '未给定订单类型或给定的类型非设定值！'
                ];
            }
            $self_type = $params['self_type'];

            foreach ($custom_sku_list as $cs) {
                # code...
                $cusres = $this->GetCustomSkus($cs['custom_sku']);
                $baseres = db::table('self_base_spu')->where('id',$cusres['base_spu_id'])->first();

//                if($baseres){
//                    if($baseres->class==2){
//                        $task_class_id = 79;
//                        if(isset($cs['order_item_id'])){
//                            $alibaba_order[] = $cs['order_item_id'];
//                        }
//
//                    }
//
//
//                    if($spu_self_type==0){
//                        $spu_self_type = $baseres->class;
//                    }else{
//                        if($spu_self_type!=$baseres->class){
//                            return [
//                                'type' => 'fail',
//                                'msg' =>  '线下采购款与线上采购款不能同时下单'.$cs['custom_sku']
//                            ];
//                        }
//                    }
//
//                }
                // 逻辑调整 手动选择线上采购单/线下采购单类型
                if ($self_type == 2){
                    $task_class_id = 79;
                    if(isset($cs['order_item_id'])){
                        $alibaba_order[] = $cs['order_item_id'];
                    }
                }

         

                
                $custom_sku_id = $cusres['id'];

                $spu_id = $cusres['spu_id'];

//                $spu_platform_id = db::table('self_spu')->where('id',$spu_id)->first()->platform_id;
//                if($spu_platform_id!=$platformId){
//                    return [
//                        'type' => 'fail',
//                        'msg' =>  '下单平台与spu平台不一致'.$cs['custom_sku']
//                    ];
//                }

                $color_id =  $cusres['color_id'];

                $is_ban = db::table('self_spu_color_isplace')->where('spu_id',$spu_id)->where('color_id',$color_id)->first();
                if($is_ban){
                    return [
                        'type' => 'fail',
                        'msg' =>  'spu+颜色已被禁用'.$cs['custom_sku']
                    ];
                }
                // $spures = db::table('self_spu')->where('id',$spu_id)->get();
                if($spu_id<=0){
                    return [
                        'type' => 'fail',
                        'msg' =>  '该库存sku无spu，请检查数据'.$cs['custom_sku']
                    ];
                }

                $onum = 0;
                foreach ($cs['num'] as $cov) {
                    # code...
                    $onum+=$cov;
                }

                $spunum[$spu_id.$color_id]['spu_id'] = $spu_id;
                $spunum[$spu_id.$color_id]['color_id']=$color_id;
                if(isset($spunum[$spu_id.$color_id]['order'])){
                    $spunum[$spu_id.$color_id]['order'] += $onum;
                }else{
                    $spunum[$spu_id.$color_id]['order'] = $onum;
                }
           
                



                if(in_array($custom_sku_id,$is_repeats)){
                    return [
                        'type' => 'fail',
                        'msg' =>  '存在重复库存sku数据，请重新检查删除重复数据'
                    ];
                }else{
                    $is_repeats[] = $custom_sku_id;
                }
                $img = $this->GetCustomskuImg($cs['custom_sku']);
                if($img==''){
                    $errcs[] = $cs['custom_sku'];
                }


            }

            foreach ($spunum as $sspu => $snum) {
                # code...
                // $spures = db::table('self_spu')->where('id',$sspu)->first();
                // $order_start_quantity = $spures->order_start_quantity;
                // if($order_start_quantity!=0){
                //     if($snum%$order_start_quantity!=0){
                //         return [
                //             'type' => 'fail',
                //             'msg' =>  '该spu下单数量非下单起订量或下单起订量的倍数，请重新下单'.$spures->spu.'起订量：'.$order_start_quantity
                //         ];
                //     }
                // }

                $spures = db::table('self_spu')->where('id',$sspu)->first();
                $basees = db::table('self_spu_color')->where('base_spu_id',$snum['spu_id'])->where('color_id',$snum['color_id'])->first();
                if($basees){
                    $order_start_quantity = $basees->order_start_quantity;
                    if($order_start_quantity!=0){
                        if($snum['order']%$order_start_quantity!=0){
                            return [
                                'type' => 'fail',
                                'msg' =>  '该spu下单数量非下单起订量或下单起订量的倍数，请重新下单'.$spures->spu.'起订量：'.$order_start_quantity.'当前量:'.$snum['order']
                            ];
                        }
                    }
                }
               
            }

            // if(count($errcs)>0){
            //     $errcsmsg = implode(",", $errcs);
            //     return [
            //         'type' => 'fail',
            //         'msg' =>  '库存sku:'.$errcsmsg.'无图片，无法下单'
            //     ];
            // }



            db::beginTransaction();    //开启事务


                $addtask['user_id'] = $user_id;
                $addtask['creattime'] = $creattime;
                $addtask['status'] = $status;
                $addtask['content'] = $content;
                $addtask['platform'] = $platform;
                $addtask['type'] = $type;
                $addtask['is_optimization'] = $is_optimization;
                $addtask['sales_market'] = $sales_market;
                $addtask['sale_crowd'] = $sale_crowd;
                $addtask['expect_date'] = $expect_date;
                $addtask['supply_user'] = $supply_user;
                $addtask['mode'] = 2;
                $addtask['shop_id'] = $shop_id;
                $addtask['tag'] = $tag;
                $addtask['platform_id'] = $platformId;
                $addtask['self_type'] = $self_type; //1线下采购款 2线上采购款
                //录入下单任务
                $task_id = DB::table('amazon_place_order_task')->insertGetId($addtask);
                if(!$task_id){
                    db::rollback();
                    return [
                        'type' => 'fail',
                        'msg' => '新增下单计划失败3623'
                    ];
                }
                $sku_count = 0;
                $order_num = 0;
                $spulist = array();
                $supplierMdl = db::table('suppliers')
                    ->get()
                    ->keyBy('Id');
                foreach ($custom_sku_list as $custom_one) {
                    $custom_sku = $custom_one['custom_sku'];
                    $custom_res = Db::table('self_custom_sku as a')->leftjoin('self_color_size as b','a.color','=','b.identifying')->where('a.custom_sku',$custom_sku)->orwhere('a.old_custom_sku',$custom_sku)->select('a.spu','a.custom_sku','a.color','a.size','b.english_name as color_name_en','b.name as color_name','a.spu_id','a.id','a.type')->first();
                    if(!$custom_res){
                        db::rollback();
                        return [
                            'type' => 'fail',
                            'msg' => '没有'.$custom_sku.'的数据'
                        ];
                    }
//                    if($custom_res->type==2){
//                        db::rollback();
//                        return [
//                            'type' => 'fail',
//                            'msg' => '组合sku无法下单，请删除后重试-'.$custom_sku
//                        ];
//                    }
                    // 增加卡控
                    if ($self_type == 2){
                        if (empty($custom_one['supplier_id'])){
                            db::rollback();
                            return [
                                'type' => 'fail',
                                'msg' => $custom_sku.'未绑定供应商！请前往spu产品信息-sku详细数据面板中绑定！'
                            ];
                        }
                        $supplier = $supplierMdl[$custom_one['supplier_id']] ?? '';
                        if (empty($supplier)){
                            db::rollback();
                            return [
                                'type' => 'fail',
                                'msg' => $custom_sku.'绑定的供应商数据有误！请前往spu产品信息-sku详细数据面板中绑定！'
                            ];
                        }
                    }
                    $custom_sku = $custom_one['custom_sku'];
                    $name_en = $custom_one['name_en']??'';
                    //录入下单表
                    $old_spu = $this->GetOldSpu($custom_res->spu);
                    if($old_spu){
                        $spulist[] = $old_spu;
                    }else{
                        $spulist[] = $custom_res->spu;
                    }
                    $num = json_encode($custom_one['num']);
//                    var_dump($custom_res);
                    $addorder['spu_id'] = $custom_res->spu_id;
                    $addorder['custom_sku_id'] = $custom_res->id;
                    $addorder['name_en'] =  $name_en;
                    $addorder['spu'] = $custom_res->spu;
                    $addorder['custom_sku'] = $custom_res->custom_sku;
                    $addorder['size'] = $custom_res->size;
                    $addorder['color_name'] = $custom_res->color_name;
                    $addorder['color_name_en'] = $custom_res->color_name_en;
                    $addorder['order_num'] =  $num;
                    $addorder['order_id'] = $task_id;

                    //亚马逊下单
                    $addorder['sku'] =  $custom_one['sku']??'';
                    $addorder['sku_id'] =  $custom_one['sku_id']??'';
                    $addorder['fasin_code'] =  $custom_one['fasin_code']??'';
                    $addorder['fasin'] =  $custom_one['fasin']??'';
                    $addorder['shop_id'] =  $custom_one['shop_id']??'';

                    $addorder['suppliers_price'] =  $custom_one['suppliers_price']??'';
                    $addorder['suppliers_id'] =  $custom_one['supplier_id']??'';



                    //修改成本价
                    $price = $custom_one['price']??0;
                    $this->UpdateCustomSkuPrice($addorder['custom_sku'],$price);



                    $insert_detail = DB::table('amazon_place_order_detail')->insert($addorder);
                    if(!$insert_detail){
                        db::rollback();
                        return [
                            'type' => 'fail',
                            'msg' => '新增下单明细数据失败3650'
                        ];
                    }
                    $order_num += array_sum($custom_one['num']);
                    $sku_count++;
                }
                $spulist = array_unique($spulist);
                $cate = DB::table('self_spu')->where('spu',$spulist[0])->orWhere('old_spu',$spulist[0])->select('base_spu_id','one_cate_id','two_cate_id','three_cate_id')->first();
                if(empty($cate)){
                    return [
                        'type' => 'fail',
                        'msg' => 'spu:'.$spulist[0].'错误,未查询到该spu数据'
                    ];
                }
                //修改计划数据
                $updatetask['sku_count'] = $sku_count;
                $updatetask['order_num'] = $order_num;
                $updatetask['spulist'] = implode(",",$spulist);
                $updatetask['one_cate_id'] = $cate->one_cate_id;
                $updatetask['two_cate_id'] = $cate->two_cate_id;
                $updatetask['three_cate_id'] = $cate->three_cate_id;
                $task_update = DB::table('amazon_place_order_task')->where('id',$task_id)->update($updatetask);
                if(!$task_update){
                    db::rollback();
                    return [
                        'type' => 'fail',
                        'msg' => '修改失败，amazon_place_order_task表3598'
                    ];
                }

                $touser_id = 0;
                $account = '';
                //新品下单polo品类如果是纯色的加上陈显爱为默认审核人，印花加上林妮燕为默认审核人
                if($type==1){
                    //女装-无袖-polo:416  女装-短袖-polo:33   女装-长袖-polo:34
                    //男装-短袖-polo:140  男装-长袖-polo:141
                    //幼童-polo:230
                    //男童-polo:238
                    //女童-短袖POLO:260
                    //陈显爱 96  林妮燕 105
                    $polos = [416,33,34,140,141,230,238,260];
                    if(in_array($cate->three_cate_id,$polos)){
                        $basespures = db::table('self_base_spu')->where('id',$cate->base_spu_id)->first();
                        if($basespures->color_style==1){
                            //纯色
                            $touser_id = 96;
                            $account = '陈显爱';
                        }else if($basespures->color_style==2){
                            //印花
                            $touser_id = 105;
                            $account = '林妮燕';
                        }
                    }

                }

                $return['account'] = $account;
                $return['user_id'] = $touser_id;
                $return['order_id'] = $task_id;
                $return['class_id'] = $task_class_id;
                $return['link'] = '/supplyChain_order_data?order_id='.$task_id;


                //1688下单记录
                if($task_class_id==79){
                    if(isset($alibaba_order)){
                        foreach ($alibaba_order as $alv) {
                            # code...
                            if(!empty($alv)){
                                $apoi['order_item_id'] = $alv;
                                $apoi['create_time'] = date('Y-m-d H:i:s',time());
                                db::table('alibaba_place_order')->insert($apoi);
                            }

                        }
                    }
                    
                }

                db::commit();// 确认
                return ['type' => 'success','data' => $return, 'msg' => '生成任务成功'];

        }else{
            return [
                'type' => 'fail',
                'msg' => 'custom_sku异常不能为空'
            ];
        }

        

    }







    //生产下单任务列表
    public function PlaceOrderTaskList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $data = DB::table('amazon_place_order_task');

        if(isset($params['user_id'])){
            $data = $data->where('user_id',$params['user_id']);
        }
        if(isset($params['id'])){
            $data = $data->where('id',$params['id']);
        }
        if(!empty($params['status'])){
            $data = $data->whereIn('status',$params['status']);
        }
        if(!empty($params['shop_id'])){
            $data = $data->where('shop_id',$params['shop_id']);
        }
        if(!empty($params['type'])){
            $data = $data->where('type',$params['type']);
        }
        if(!empty($params['supply_user'])){
            $data = $data->where('supply_user','like','%'.$params['supply_user'].'%');
        }
        if(!empty($params['spu'])){
            $data = $data->where('spulist','like','%'.$params['spu'].'%');
        }
        if(!empty($params['one_cate_id'])){
            $data = $data->whereIn('one_cate_id',$params['one_cate_id']);
        }
        if(!empty($params['two_cate_id'])){
            $data = $data->whereIn('two_cate_id',$params['two_cate_id']);
        }
        if(!empty($params['three_cate_id'])){
            $data = $data->whereIn('three_cate_id',$params['three_cate_id']);
        }
        if(!empty($params['mode'])){
            $data = $data->where('mode',$params['mode']);
        }
        if(!empty($params['self_type'])){
            $data = $data->where('self_type',$params['self_type']);
        }


        $totalNum = $data->count();
        $data = $data->offset($page)->limit($limit)->orderBy('creattime','desc')->get();

        // $namearr = [];
        foreach ($data as $k=>$v) {
            //获取品类
            $one_cate = $this->GetCategory($v->one_cate_id)['name'];
            $two_cate = $this->GetCategory($v->two_cate_id)['name'];
            $three_cate = $this->GetCategory($v->three_cate_id)['name'];
            $data[$k]->category = $one_cate.'-'.$two_cate.'-'.$three_cate;
            # code...
            $v->account = '';
            if($v->user_id>0){
                $v->account =  $this->GetUsers($v->user_id)['account'];
            }

            $v->shop_name = '';
            if($v->shop_id>0){
                $v->shop_name =  $this->GetShop($v->shop_id)['shop_name'];
            }
            $data[$k]->platform_name = $this->GetPlatform($v->platform_id)['name']??'';

            $names = '';

            if(isset($v->supply_user)){
                $users = explode(',',$v->supply_user);
                $username = [];
                foreach ($users as $id) {
                    # code...
                    $username[] =  $this->GetUsers($id)['account'];
                }
    
                if(is_array($username)){
                    $names = implode(',',$username)??' ';
                }
                       
             }
             $data[$k]->supply_name = $names;

            $data[$k]->tag_name = '';
            $data[$k]->tag_id = 0;
            if($data[$k]->tag){
                $tag_name = DB::table('amazon_tag')->where('id',$data[$k]->tag)->first();
                if(!empty($tag_name)){
                    $data[$k]->tag_name = $tag_name->name;
                    $data[$k]->tag_id = $tag_name->id;
                }
            }

            $expiretime = strtotime(date($data[$k]->creattime,strtotime("+7 days")));
            if($expiretime>time()){
                $data[$k]->is_expire = '已过期';
            }else{
                $data[$k]->is_expire = '周期进行中';
            }
            //  $namearr[$k] = $names;

            //  $v->supply_name = $names;
            $contractMdl = db::table('cloudhouse_contract_total')
                ->where('bind_place_ids', 'like', '%'.$v->id.'%')
                ->get(['contract_no']);
            if ($contractMdl->isNotEmpty()){
                $contractNo = array_column($contractMdl->toArrayList(), 'contract_no');
            }else{
                $contractNo = '';
            }
            $data[$k]->contract_no = $contractNo;
            $data[$k]->status_name = Constant::AMAZON_PLACE_ORDER_TASK_STATUS[$v->status] ?? '';
        }

        return [
            'data' => $data,
            'totalNum' => $totalNum,
        ];

    }

    //生产下单列表-分类
    public function PlaceOrderDetailByCate($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        // $page  =  $pagenum- 1;
        // if($page!=0){
        //     $page  =  $page * $limit;
        // }

        $data = DB::table('amazon_place_order_detail as a')->leftjoin('self_spu as b','a.spu','=','b.spu')->leftjoin('amazon_place_order_task as c','c.id','=','a.order_id')->where('c.status','!=','-1')->select('a.custom_sku','b.spu','b.old_spu','b.one_cate_id','b.two_cate_id','b.three_cate_id');
        if(isset($params['one_cate_id'])){
            $data = $data ->where('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $data = $data ->where('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $data = $data ->where('b.three_cate_id',$params['three_cate_id']);
        }

        if(isset($params['spu'])){
            $data = $data ->where(function($query) use($params){
                $query->where('b.spu','like','%'.$params['spu'].'%')->orwhere('b.old_spu','like','%'.$params['spu'].'%');
            });
        }

        // $totalNum = $data->groupby('a.custom_sku')->count();



        $data = $data->groupby('a.custom_sku')->get();
        $order_total = 0;

        // foreach ($data as $v) {
        //     # code...
        //        $order = json_decode($v->order_num,true);
        //        $o_num = 0;
        //        foreach ($order as $num) {
        //            # code...
        //            $o_num+=$num;
        //        }

        //        $v->ordernum = $o_num;
        //        $order_total+= $v->ordernum; 
        // }

        $data = json_decode(json_encode($data),true);

        $totalNum = count($data);

        $return = [];
        $ni = 0;
        $start = ($pagenum-1)*$limit;
        for ($i=$start; $i < $pagenum*$limit; $i++) { 
            # code...
            if(isset($data[$i])){
                $return[$ni] = $data[$i];
                $ni++;
            }
        }


        foreach ($return as&$v) {
            # code...
            $v['img'] = $this->GetCustomskuImg($v['custom_sku']);
            //大类
            $v['one_cate'] = '';
            $one_cate = $this->GetCategory($v['one_cate_id']);
            if($one_cate){
                $v['one_cate']  = $one_cate['name'];
            }

            //二类
            $v['two_cate']  = '';
            $two_cate = $this->GetCategory($v['two_cate_id']);
            if($two_cate){
                $v['two_cate']  = $two_cate['name'];
            }

            //三类
            $v['three_cate']  = '';
            $three_cate = $this->GetCategory($v['three_cate_id']);
            if($three_cate){
                $v['three_cate']  = $three_cate['name'];
            }

            $orderes = db::table('amazon_place_order_detail')->where('custom_sku',$v['custom_sku'])->get()->toArray();
            $orders = array_column($orderes,'order_num'); 
            $item_order = 0;
            foreach ($orders as $order) {
                # code...
                $order = json_decode($order,true);
                $o_num = 0;
                foreach ($order as $num) {
                    # code...
                    $o_num+=$num;
                }
                $item_order+= $o_num;
            }
            $v['ordernum'] = $item_order;
            $order_total+=$v['ordernum'];
          
        }
        return [
            'data' => $return,
            'totalNum' => $totalNum,
            'order_total'=> $order_total,
        ];
    }


    //生产下单合并导出
    public function PlaceOrderSumExport($params){

        // if(!isset($params['ids'])||!is_array($params['ids'])){
        //     return [
        //         'type' => 'fail',
        //         'msg' => 'ids必传'
        //     ];
        // }

        if (strstr($params['ids'], '，')) {
            $symbol = '，';
        } elseif (strstr($params['ids'], ',')) {
            $symbol = ',';
        } else {
            $symbol = '';
        }
        if ($symbol) {
            $ids = explode($symbol,$params['ids']);
        }else{
            $ids[0] = $params['ids'];
        }

        $user_id = $params['user_id']??1;
        $data = DB::table('amazon_place_order_detail as a')->leftjoin('amazon_place_order_task as b','a.order_id','=','b.id')->whereIn('b.id',$ids)->select('a.custom_sku','a.order_num','a.spu','a.size','a.color_name','a.color_name_en','b.user_id','b.expect_date','b.id')->get();

        //分组
        //运营
        $user_ids = [];
        //spu+颜色
        $spu_colors = [];
        foreach ($data as $v) {
            # code...
            $user_ids['u'.$v->user_id.'-'.$v->id] = $this->GetUsers($v->user_id)['account'];
            // $k = $v->spu.$v->color_name_en;
            // $spu_colors[$k] = $k;
            $spu_colors[$v->custom_sku] = $v->custom_sku;
        }


        $new_data = [];
        // foreach ($data as $v) {

        $user_idss = [];

        $spucolororder = [];

        foreach ($spu_colors as $sv) {
            foreach ($data as $v) {
                # code...
                $k = $v->custom_sku;
                if($k==$sv){
                        $thisSpu = $this->GetOldSpu($v->spu);
                        if($thisSpu){
                            $new_data[$k]['spu'] = $thisSpu;
                        }else{
                            $new_data[$k]['spu'] = $v->spu;
                        }

                        $new_data[$k]['img'] = $this->GetCustomskuImg($v->custom_sku);
                        $new_data[$k]['color_name_en'] = $v->color_name_en;
                        $new_data[$k]['color_name'] = $v->color_name;
                        $new_data[$k]['size'] = $v->size;
                        $new_data[$k]['order_total'] = 0;
        
                        $order = json_decode($v->order_num,true);
                        $order_num = 0;
                        foreach ($order as $ov) {
                            # code...
                            $order_num+=$ov;
                        }
                        $expect_date = json_decode($v->expect_date,true);
                        
                        if(isset($spucolororder[$new_data[$k]['spu'].$v->color_name_en])){
                            $spucolororder[$new_data[$k]['spu'].$v->color_name_en] +=  $order_num;
                        }else{
                            $spucolororder[$new_data[$k]['spu'].$v->color_name_en] =  $order_num;
                        }

                        foreach ($user_ids as $uv =>$vv) {
                            # code...
                            if($uv=='u'.$v->user_id.'-'.$v->id){
                                foreach ($order as $ok => $ov) {
                                    # code...
                                    $pc = $ok+1;
                                    $user_idss['u'.$v->user_id.'-'.$v->id.$ok] = $this->GetUsers($v->user_id)['account']."(".$v->id."第".$pc."批".$expect_date[$ok].")";
                                    $new_data[$k][$uv.$ok] = $ov;
                                    $new_data[$k]['orders'][] = $ov;
                                    // $new_data[$k]['order_total'] +=$ov;
                                }
                               
                            }
                            
                        }
                        // $new_data[$k]['order_total'] = 0;
                       
                }
            }
        }
        

        foreach ($new_data as &$nv) {
            # code...
            $nv['order_total'] = array_sum($nv['orders']);
        }

        $is_color_ary = [];

        foreach ($new_data as &$nv) {
            foreach ($user_idss as $k => $v) {
                # code...
                if(!isset($nv[$k])){
                    $nv[$k] = 0;
                }
            }
            $key = $nv['spu'].$nv['color_name_en'];
            if(!in_array($key,$is_color_ary)){
                $nv['spu_color_count'] =  $spucolororder[$key];
                $is_color_ary[] = $key;
            }else{
                $nv['spu_color_count'] = '';
                $nv['img'] = '';
            }
            # code...
        }


        $p['title']='生产下单合并表'.time();

        $list = [
            'spu'=>'款号',
            'img'=>'图片',
            'color_name'=>'中文颜色',
            'color_name_en'=>'英文颜色',
            'size'=>'尺码',
            'order_total'=>'订单数量',
            'spu_color_count'=>'单款单色合计数量'
        ];

        // var_dump($user_ids);
        $p['title_list']  = $list+$user_idss;
        $p['data'] =  $new_data;
        $p['user_id'] = $user_id;
        $p['type'] = '生产下单-合并导出';

       
        $job = new ExcelTaskController();
        try {
            $job::runJob($p);
        } catch(\Exception $e){
            return ['type' => 'fail', 'msg' => '加入队列失败'];
        }
        return ['type' => 'success','msg' => '加入队列成功'];
        //  $this->place_excel_expord($p);
     
    }


    //excel 导出任务
    public function ExcelTaskList($params){
        $user_id = $params['user_id'];
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;


        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }


        $totalNum=  DB::table('excel_task')->where('user_id',$user_id)->count();
        $list = DB::table('excel_task')->where('user_id',$user_id)->offset($page)->limit($limit)->orderby('id','desc')->get();

        foreach ($list as $v) {
            # code...
            $v->path = 'http://116.62.169.253:9080/'.$v->path;
        }
        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    //生产下单任务详情
    public function PlaceOrderTaskDetailList($params){

        $data = DB::table('amazon_place_order_detail');

        $order = DB::table('amazon_place_order_task');

        $order->desc = '';
        $order->yj_saletime = '';
        $task_id = 0;
        
        if(isset($params['order_id'])){
            $data = $data->where('order_id',$params['order_id']);
            $order = $order->where('id',$params['order_id']);
            //获取任务id
            $order_id = substr(substr(json_encode(array("order_id" => $params['order_id'])), 1), 0, -1);
            $task = DB::table('tasks')->where('ext','like',"%{$order_id}%")->select('Id','desc','ext')->first();
        }

        $totalNum = $data->count();
        $data = $data->get();
        $order = $order->first();
        if(!empty($task)){
            $task_id = $task->Id;
            //备注
            $order->desc = $task->desc;
            //预计销售时间
            $ext = json_decode($task->ext,true);
            if(isset($ext['start_time'])&&isset($ext['end_time'])){
                $order->yj_saletime = $ext['start_time'].'~'.$ext['end_time'];
            }
        }
        if(!$order){
            return [
                'type' => 'fail',
                'msg' => '无此下单计划'
            ];
        }

        $expiretime = strtotime(date($order->creattime,strtotime("+7 days")));
        if($expiretime>time()){
            $order->is_expire = '已过期';
        }else{
            $order->is_expire = '周期进行中';
        }

        //期望交期
        $order->expect_date = json_decode($order->expect_date,true);
        $order->account = '';
        $order->shop_name = '';
        $order->supply_name = '';
        $order->tag_name = '';
        if($order->type==1){
            $user_list = explode(',',$order->user_id);
            $shop_list = explode(',',$order->shop_id);
            foreach ($user_list as $u){
                $order->account .= $this->GetUsers($u)['account'].',';
            }
            foreach ($shop_list as $s){
                $order->shop_name .= $this->GetShop($s)['shop_name'].',';
            }
        }else{
            if($order->user_id>0){
                $order->account =  $this->GetUsers($order->user_id)['account'];
            }
            if($order->shop_id>0){
                $order->shop_name =  $this->GetShop($order->shop_id)['shop_name'];
            }
            $tag_name = DB::table('amazon_tag')->where('id',$order->tag)->first();
            if(!empty($tag_name)){
                $order->tag_name = $tag_name->name;
            }
        }


         if(isset($order->supply_user)){
            $users = explode(',',$order->supply_user);
            $username = [];
            foreach ($users as $v) {
                # code...
                $username[] =  $this->GetUsers($v)['account'];
            }

             $order->supply_name = implode(',',$username);
          
         }

        $order->account = rtrim($order->account,',');
        $order->shop_name = rtrim($order->shop_name,',');

        foreach ($data as $v) {
            # code...
            $v->order_num = json_decode($v->order_num,true);
            //创建者
            $v->img = '';
            $spudata =DB::table('self_spu')->where('id',$v->spu_id)->select('platform_id','spu','old_spu','base_spu_id')->first();
            if(empty($spudata)){
                return [
                    'type' => 'fail',
                    'msg' => '没有'.$v->spu.'的数据'
                ];
            }
            if($spudata->old_spu){
                $v->spu = $spudata->old_spu;
            }
            $v->amazonSpu = '';
            if($spudata->platform_id!=5) {
                $amazonSpu = DB::table('self_spu')->where('base_spu_id', $spudata->base_spu_id)->where('platform_id', 5)->select('spu', 'old_spu')->first();
                if (!empty($amazonSpu)) {
                    if ($amazonSpu->old_spu) {
                        $v->amazonSpu = $amazonSpu->old_spu;
                    } else {
                        $v->amazonSpu = $amazonSpu->spu;
                    }
                }
            }

            // $colors = Db::table('self_color_size')->where('english_name',$v->color_name_en)->first();
            // if($colors){
            //     $imgs = Db::table('self_spu_color')->where('spu',$spus)->where('color_id',$colors->id)->first();
            //     if($imgs){
            //         $v->img = $imgs->img;
            //     }
    
            // }
//            if($order->type==2){
                $cus = Db::table('self_custom_sku')->where('custom_sku',$v->custom_sku)->orWhere('old_custom_sku',$v->custom_sku)->first();
               
                if(empty($cus)){
                    return [
                        'type' => 'fail',
                        'msg' => '系统没有'.$v->custom_sku.'的数据'
                    ];
                }
                //生产中的库存
                $v->surplus_num =  $this->GetSurplusNum($cus->id);
                if($cus->old_custom_sku){
                    $v->custom_sku = $cus->old_custom_sku;
                }
                $v->img = $this->GetCustomskuImg($v->custom_sku);
                // $v->custom_sku_price = $this->GetCustomSkuPrice($v->custom_sku);
                $v->custom_sku_price  = $v->suppliers_price;
                //获取fba库存
                $sku = Db::table('self_sku')->where('custom_sku_id',$cus->id)->where('shop_id',$order->shop_id)->select('sku','id','old_sku')->first();
                $v->fba_inventory = 0;
                $v->lastmonth_salesale = 0;
                $v->thismonth_sale = 0;
                $v->return_rate = 0;
                $v->day_order = 0;
                if(!empty($sku)){
                    $sku = json_decode(json_encode($sku),true);
                    if($sku['old_sku']){
                        $skulist = $sku['old_sku'];
                    }else{
                        $skulist = $sku['sku'];
                    }
                    $fba_res = $this->getFbaInventory([$skulist],'sku');
                    if($fba_res){
                        foreach ($fba_res as $inven){
                            $v->fba_inventory += $inven['in_stock_num']+$inven['in_bound_num']+$inven['transfer_num'];
                        }
                    }else{
                        $v->fba_inventory = 0;
                    }
                    //获取月销量和历史5个月销量
                    // $month = date('m');
//                     $start_time = date('Y-m-01 00:00:00');
//                     $end_time = date('Y-m-01 00:00:00',strtotime("+1 months"));
//                     $monthsales = Db::table('amazon_order_item')->where('seller_sku',$skulist)->where('shop_id',$order->shop_id)->where('order_status','!=','Canceled')->whereBetween('amazon_time', [$start_time, $end_time])->select('quantity_ordered')->get();
// //               var_dump($skulist);
//                var_dump($monthsales);
                    // if(!empty($monthsales)){
                    //     $monthsales = json_decode(json_encode($monthsales),true);
                    //     $this_month = array_column($monthsales,'quantity_ordered');
                    //     $v->thismonth_sale = array_sum($this_month);
                    // }else{
                    //     $v->thismonth_sale = 0;
                    // }
                //     $lastmonth = $month-5;
                //     if($lastmonth<0){
                //         $year = date('Y',strtotime("-1 year"));
                //         $lastmonth = 12+$lastmonth;
                //     }elseif($lastmonth==0){
                //         $year = date('Y',strtotime("-1 year"));
                //         $lastmonth = 12;
                //     }else{
                //         $year = date('Y');
                //     }
                //    if($lastmonth<10){
                //        $lastmonth = '0'.$lastmonth;
                //    }
                    //历史5个月销量
                    // $lastmonth_sales = false;
                    // $lastmonth_sales = $this->getMonthSales($skulist,$order->shop_id,$lastmonth,$year);
                    // if($lastmonth_sales){
                    //     $v->lastmonth_salesale = $lastmonth_sales;
                    // }else{
                    //     $v->lastmonth_salesale = 0;
                    // }




                    // $r_start_time = date($year.'-'.$month.'-01 00:00:00');
                    // $r_start_int = strtotime($r_start_time);
                    // $r_end_int = strtotime("+5 months",$r_start_int);
                    // $r_end_time = date('Y-m-d H:i:s',$r_end_int);
                    //前五月退货数量
                    $s_5_start = date('Y-m-d',strtotime("-150 day"));
                    $s_5_end = date('Y-m-d',time());
                    $return_num = db::table('amazon_return_order')->where('sku_id',$sku['id'])->whereBetween('beijing_date', [$s_5_start, $s_5_end])->sum('quantity');
    
                    $v->history_order = $this->GetOrderPlaceOrderBySku($sku['id'],$order->shop_id);

                    //五月销量
                    $v->lastmonth_salesale =  $v->history_order['a150']['order'];
                    //当月销量
                    $v->thismonth_sale = $v->history_order['this_moon']['order'];

                    if($v->history_order['a150']['order']>0&&$return_num){
                        $v->return_rate  = round(($return_num/$v->history_order['a150']['order'])*100,2);
                    }

                    if($v->history_order['a14']['order']>0){
                        $v->day_order = round($v->history_order['a14']['order']/14,2);
                    }

                    $v->fba_inventory_day = 0;
                    if($v->day_order>0&&$v->fba_inventory>0){
                        $v->fba_inventory_day = ceil($v->fba_inventory/$v->day_order);
                    }

                    
                  
                    
                    // if($return_num>0&&$lastmonth_sales>0){
                    //     $v->return_rate  = round(($return_num/$lastmonth_sales)*100,2);
                    // }
                    $v->sku_id = $sku['id'];

                }
                //本地仓库存
                $tongan = 0;
                $quanzhou = 0;
                $cloud = $cus->cloud_num;
                // $here_res = false;
                $here_res = $this->getHereInventory([$v->custom_sku],'custom_sku');
                if(!empty($here_res)){
                    if($here_res['tongan']){
                        $tongan = $here_res['tongan'][$v->custom_sku];
                    }
                    if($here_res['quanzhou']){
                        $quanzhou = $here_res['quanzhou'][$v->custom_sku];
                    }
                }
                $v->here_inventory_day = 0;
                $v->here_inventory = $tongan+$quanzhou+$cloud;

                if($v->day_order>0&&$v->here_inventory>0){
                    $v->here_inventory_day = ceil($v->here_inventory/$v->day_order);
                }
//            }
                //如果是欧码，需要查询美码
                if($order->sales_market==2){
                    $v->us_inventory = 0;
                    $v->us_custom_sku = '';
                    $us_tongan = 0;
                    $us_quanzhou = 0;
                    

                    $us_spu = db::table('self_spu')->where('base_spu_id',$spudata->base_spu_id)->where('market','U')->first();
                    if($us_spu){
                        $us_cus = db::table('self_custom_sku')->where('spu_id',$us_spu->id)->where('color',$cus->color)->where('size',$cus->size)->first();
                        if($us_cus){
                            $us_here_res = $this->getHereInventory([$us_cus->custom_sku],'custom_sku');
                            if(!empty($us_here_res)){
                                if($us_here_res['tongan']){
                                    $us_tongan = $us_here_res['tongan'][$us_cus->custom_sku];
                                }
                                if($us_here_res['quanzhou']){
                                    $us_quanzhou = $us_here_res['quanzhou'][$us_cus->custom_sku];
                                }
                            }
                            $v->us_custom_sku = $us_cus->custom_sku;
                            $v->us_inventory = $us_tongan+$us_quanzhou+$us_cus->cloud_num;
                        }
                     
                    }

                }

        }

        return [
            'task_id'=>$task_id,
            'order'=>$order,
            'detail' => $data,
            'totalNum' => $totalNum,
        ];

    }


    //获取sku订单各时间段数据
    public function GetOrderPlaceOrderBySku($sku_id,$shop){
        $res = Db::table('amazon_order_item')->where('sku_id',$sku_id)->where('shop_id',$shop)->where('order_status','!=','Canceled')->select('amazon_time','quantity_ordered')->get();
        $y = date("Y",strtotime("-1 year")); 
        $m = date('m');
        $query = [];
        //7天
        $s_1['start'] = strtotime("-7 day");
        $s_1['end'] = time();
        $s_1['order'] = 0;
        $query['a7'] = $s_1;
        //14天
        $s_2['start'] = strtotime("-14 day");
        $s_2['end'] = time();
        $s_2['order'] = 0;
        $query['a14'] = $s_2;
        //30天
        $s_3['start'] = strtotime("-30 day");
        $s_3['end'] = time();
        $s_3['order'] = 0;
        $query['a30'] = $s_3;

        //60天
        $s_4['start'] = strtotime("-60 day");
        $s_4['end'] = time();
        $s_4['order'] = 0;
        $query['a60'] = $s_4;


        //前五月销量
        $s_5['start'] = strtotime("-150 day");
        $s_5['end'] = time();
        $s_5['order'] = 0;
        $query['a150'] = $s_5;

        //当月销量
        $s_6['start'] = strtotime(date("Y-m-01"));
        $s_6['end'] = time();
        $s_6['order'] = 0;
        $query['this_moon'] = $s_6;


        //1月
        $s_7['start'] = strtotime($y."-01-01");
        $s_7['end'] = strtotime($y."-02-01");
        $s_7['order'] = 0;
        $query['s1'] = $s_7;
        //2月
        $s_8['start'] = strtotime($y."-02-01");
        $s_8['end'] = strtotime($y."-03-01");
        $s_8['order'] = 0;
        $query['s2'] = $s_8;
        //3月
        $s_9['start'] = strtotime($y."-03-01");
        $s_9['end'] = strtotime($y."-04-01");
        $s_9['order'] = 0;
        $query['s3'] = $s_9;
        //4月
        $s_10['start'] = strtotime($y."-04-01");
        $s_10['end'] = strtotime($y."-05-01");
        $s_10['order'] = 0;
        $query['s4'] = $s_10;
        //5月
        $s_11['start'] = strtotime($y."-05-01");
        $s_11['end'] = strtotime($y."-06-01");
        $s_11['order'] = 0;
        $query['s5'] = $s_11;
        //6月
        $s_12['start'] = strtotime($y."-06-01");
        $s_12['end'] = strtotime($y."-07-01");
        $s_12['order'] = 0;
        $query['s6'] = $s_12;
        //7月
        $s_7['start'] = strtotime($y."-07-01");
        $s_7['end'] = strtotime($y."-08-01");
        $s_7['order'] = 0;
        $query['s7'] = $s_7;
        //8月
        $s_8['start'] = strtotime($y."-08-01");
        $s_8['end'] = strtotime($y."-09-01");
        $s_8['order'] = 0;
        $query['s8'] = $s_8;
        //9月
        $s_9['start'] = strtotime($y."-09-01");
        $s_9['end'] = strtotime($y."-10-01");
        $s_9['order'] = 0;
        $query['s9'] = $s_9;
        //10月
        $s_10['start'] = strtotime($y."-10-01");
        $s_10['end'] = strtotime($y."-11-01");
        $s_10['order'] = 0;
        $query['s10'] = $s_10;
        //11月
        $s_11['start'] = strtotime($y."-11-01");
        $s_11['end'] = strtotime($y."-12-01");
        $s_11['order'] = 0;
        $query['s11'] = $s_11;
        //12月
        $s_12['start'] = strtotime($y."-12-01");
        $s_12['end'] = strtotime($y."-12-31 23:59:59");
        $s_12['order'] = 0;
        $query['s12'] = $s_12;

        foreach ($res as $v) {
            # code...
            $time = strtotime($v->amazon_time);
            foreach ($query as &$qv) {
                # code...
                //订单时间戳小于结束时间，大于开始时间
                // echo '订单时间'.$time."\n";
                // echo '结束时间'.$qv['end']."\n";
                // echo '开始时间'.$qv['start']."\n";
                if($time<=$qv['end']&&$time>=$qv['start']){
                    // echo "符合\n";
                    $qv['order']+=$v->quantity_ordered;
                }
            }
        }

        return $query;
    }

    public function GetSurplusNum($custom_sku_id){
            //    DB::connection()->enableQueryLog(); // 开启监听sql

       $total =  db::table('cloudhouse_custom_sku as a')->leftjoin('cloudhouse_contract as b','a.contract_no','=','b.contract_no')->where('a.custom_sku_id',$custom_sku_id)->where('b.status',1)->groupby('a.id')->select('a.id','a.num')->get();
    //    var_dump(DB::getQueryLog());exit(); // 打印sql
        $total_num = 0;
        foreach ($total as $v) {
            # code...
            $total_num+=$v->num;
        }
       $out = DB::table('goods_transfers_detail as a')
       ->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')
       ->where('b.type',1)
       ->where('a.custom_sku_id',$custom_sku_id)
       ->groupby('a.id')
       ->select('a.receive_num','a.id')
       ->get();
       $out_num = 0;
       foreach ($out as $v) {
           # code...
           $out_num+=$v->receive_num;
       }
       $SurplusNum = 0;
    //    echo $total_num."\n";
    //    echo $out_num."\n";
       $SurplusNum = $total_num -$out_num;
       return $SurplusNum;
    }

    //集体生产下单任务
    public function TeamPlaceOrderTaskByOne($params){

        $day = date("l");
        // if($day=='Tuesday'||$day=='Monday'){
        //     return [
        //         'type' => 'fail',
        //         'msg' => '非下单日!无法下单!请在周三，周四，周五，周六，周日提交下单!'
        //     ];
        // }
         //下单人

        $user_id = $params['user_id'];
        //下单时间
        $creattime = date('Y-m-d H:i:s',time());
        //下单状态 0.未发布任务1.已发布任务，待审核2.已审核，待录入艾诺科3.已录入艾诺科
        $status = 0;

        $content = $params['content']??'';
        //类型1.新品下单 2.旧品翻单
        $type = $params['type']??1;

        //销售市场1.美国 2.欧洲 3.日本
        $sales_market = $params['sales_market'];
        //销售人群1.成年男性 2.成年女性 3.中大童 4.幼童
        $sale_crowd = $params['sale_crowd'];
        //是否优化尺寸 1.是 2.否
        $is_optimization = $params['is_optimization'];

        //吊牌
        $tag = $params['tag'];
        //分几批期望交期
        $batch = count($params['expect_date']);

        $expect_date = json_encode($params['expect_date']);

        //店铺
        $shop_id = $params['shop_id']??0;


        if(isset($params['custom_sku_list'])){

            $custom_sku_list =  $params['custom_sku_list'];

            $errcs = [];
            $is_repeats = [];
            $spu_cate = '';
            foreach ($custom_sku_list as $cs) {
                # code...
                // $custom_sku_id = $this->GetCustomSkuId($cs['custom_sku']);
                $cus = $this->GetCustomSkus($cs['custom_sku']);
                $spus = $this->GetSpu($cus['spu_id']);
                $cates = $spus['one_cate_id'].'-'.$spus['two_cate_id'].'-'.$spus['three_cate_id'];
                if(empty($spu_cate)){
                    $spu_cate = $cates;
                }else{
                    if($cates!=$spu_cate){
                        return [
                            'type' => 'fail',
                            'msg' =>  '同一品类的库存sku才能下单，请删除此库存sku后重试.'.$cs['custom_sku']
                        ];
                    }
                }

                $custom_sku_id = $cus['id'];

                $custype = $cus['type'];
                if($custype==2){
                    return [
                        'type' => 'fail',
                        'msg' =>  '组合库存sku无法下单,请删除后重试'.$cs['custom_sku']
                    ];
                }
                if(in_array($custom_sku_id,$is_repeats)){
                    return [
                        'type' => 'fail',
                        'msg' =>  '存在重复库存sku数据，请重新检查删除重复数据'
                    ];
                }else{
                    $is_repeats[] = $custom_sku_id;
                }
                // $img = $this->GetCustomskuImg($cs['custom_sku']);
                // if($img==''){
                //     $errcs[] = $cs['custom_sku'];
                // }
            }

            if(count($errcs)>0){
                $errcsmsg = implode(",", $errcs);
                return [
                    'type' => 'fail',
                    'msg' =>  '库存sku:'.$errcsmsg.'无图片，无法下单'
                ];
            }



            db::beginTransaction();    //开启事务


            $addtask['content'] = $params['content']??'';
            $addtask['user_id'] = $user_id;
            $addtask['creattime'] = $creattime;
            $addtask['status'] = $status;
            $addtask['content'] = $content;
            $addtask['type'] = $type;
            $addtask['is_optimization'] = $is_optimization;
            $addtask['sales_market'] = $sales_market;
            $addtask['sale_crowd'] = $sale_crowd;
            $addtask['expect_date'] = $expect_date;
            $addtask['shop_id'] = $shop_id;
            $addtask['tag'] = $tag;
            $addtask['batch'] = $batch;
            //录入下单任务

            $task_id = DB::table('amazon_team_task_one')->insertGetId($addtask);
            if(!$task_id){
                db::rollback();
                return [
                    'type' => 'fail',
                    'msg' => '新增下单计划失败'
                ];
            }
            

            $sku_count = 0;
            $order_num = 0;
            $spulist = array();
            foreach ($custom_sku_list as $custom_one) {
                $custom_sku = $custom_one['custom_sku'];
                $custom_res = Db::table('self_custom_sku as a')->leftjoin('self_color_size as b','a.color','=','b.identifying')->where('a.custom_sku',$custom_sku)->orwhere('a.old_custom_sku',$custom_sku)->select('a.spu','a.custom_sku','a.color','a.size','b.english_name as color_name_en','b.name as color_name','a.spu_id','a.id')->first();
                if(!$custom_res){
                    db::rollback();
                    return [
                        'type' => 'fail',
                        'msg' => '没有'.$custom_sku.'的数据'
                    ];
                }
                $custom_sku = $custom_one['custom_sku'];
                $name_en = $custom_one['name_en']??'';
                //录入下单表
                // $old_spu = $this->GetOldSpu($custom_res->spu);
                // if($old_spu){
                //     $spulist[] = $old_spu;
                // }else{
                //     $spulist[] = $custom_res->spu;
                // }

                $num = json_encode($custom_one['num']);
//                    var_dump($custom_res);
                $addorder['spu_id'] = $custom_res->spu_id;
                $addorder['custom_sku_id'] = $custom_res->id;
                $addorder['name_en'] =  $name_en;
                $spu = $this->GetOldSpu($custom_res->spu);
                $spulist[] = $spu;
                $addorder['spu'] = $spu;
                $addorder['custom_sku'] = $custom_res->custom_sku;
                $addorder['size'] = $custom_res->size;
                $addorder['color_name'] = $custom_res->color_name;
                $addorder['color_name_en'] = $custom_res->color_name_en;
                $addorder['order_num'] =  $num;
                $addorder['report_num'] =  $num;
                $addorder['order_id'] = $task_id;
                $insert_detail = DB::table('amazon_team_task_detail')->insert($addorder);
                if(!$insert_detail){
                    db::rollback();
                    return [
                        'type' => 'fail',
                        'msg' => '新增下单明细数据失败'
                    ];
                }
                $order_num += array_sum($custom_one['num']);
                $sku_count++;
            }
            $spulist = array_unique($spulist);
            // var_dump($spulist);
            $cate = DB::table('self_spu')->where('spu',$spulist[0])->orWhere('old_spu',$spulist[0])->select('one_cate_id','two_cate_id','three_cate_id')->first();
            if(empty($cate)){
                return [
                    'type' => 'fail',
                    'msg' => 'spu错误'
                ];
            }
            //修改计划数据
            $updatetask['sku_count'] = $sku_count;
            $updatetask['order_num'] = $order_num;
            $updatetask['spulist'] = implode(",",$spulist);
            $updatetask['one_cate_id'] = $cate->one_cate_id;
            $updatetask['two_cate_id'] = $cate->two_cate_id;
            $updatetask['three_cate_id'] = $cate->three_cate_id;
            $task_update = DB::table('amazon_team_task_one')->where('id',$task_id)->update($updatetask);
            if(!$task_update){
                db::rollback();
                return [
                    'type' => 'fail',
                    'msg' => '修改失败，amazon_team_task_one表'
                ];
            }
            
            $return['order_id'] = $task_id;
            // $return['link'] = '/supplyChain_order_data?order_id='.$task_id;
            db::commit();// 确认
            return ['type' => 'success','data' => $return, 'msg' => '生成任务成功'];

        }else{
            return [
                'type' => 'fail',
                'msg' => 'custom_sku异常不能为空'
            ];
        }
    }


    //个人订单删除
    public function TeamPlaceOrderTaskByOneDel($params){
        $id = $params['id'];
        DB::table('amazon_team_task_one')->where('id',$id)->delete();
        DB::table('amazon_team_task_detail')->where('order_id',$id)->delete();
        return['type'=>'success','msg'=>'删除成功'];
    }

    //个人订单修改
    public function TeamPlaceOrderTaskByOneupdate($params){
        $id = $params['id']??0;
        if($id<1){
            return['type'=>'fail','msg'=>'请输入id'];
        }
        $content = $params['content']??'';
        //类型1.新品下单 2.旧品翻单
        $type = $params['type']??1;

        //销售市场1.美国 2.欧洲 3.日本
        $sales_market = $params['sales_market'];
        //销售人群1.成年男性 2.成年女性 3.中大童 4.幼童
        $sale_crowd = $params['sale_crowd'];
        //是否优化尺寸 1.是 2.否
        $is_optimization = $params['is_optimization'];

        //吊牌
        $tag = $params['tag'];
        //分几批期望交期
        $batch = count($params['expect_date']);

        $expect_date = json_encode($params['expect_date']);

        //店铺
        $shop_id = $params['shop_id']??0;


        $addtask['content'] = $params['content']??'';
        $addtask['content'] = $content;
        $addtask['type'] = $type;
        $addtask['is_optimization'] = $is_optimization;
        $addtask['sales_market'] = $sales_market;
        $addtask['sale_crowd'] = $sale_crowd;
        $addtask['expect_date'] = $expect_date;
        $addtask['shop_id'] = $shop_id;
        $addtask['tag'] = $tag;
        $addtask['batch'] = $batch;
        //录入下单任务
        DB::table('amazon_team_task_one')->where('id',$id)->update($addtask);
        return['type'=>'success','msg'=>'修改成功'];
    }



     //生产下单任务列表-单人
     public function TeamPlaceOrderTaskByOneList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $data = DB::table('amazon_team_task_one');

        if(isset($params['user_id'])){
            $data = $data->where('user_id',$params['user_id']);
        }
        if(isset($params['id'])){
            $data = $data->where('id',$params['id']);
        }
        if(!empty($params['status'])){
            $status = [];
            $statuss = [];
           foreach ($params['status'] as $statu) {
            # code...
                if($statu>=2){
                    $statuss[] = $statu;
                    // $task = db::table('amazon_place_order_task')->where('mode',1)->where('status','>=',2)->get();
                    // var_dump($task);
                }else{
                    $status[] = $statu;
                }
           }

           if(count($status)>0){
            $data = $data->whereIn('status',$params['status']);
           }

           if(count($statuss)>0){
            $task = db::table('amazon_place_order_task')->where('mode',1)->whereIn('status',$statuss)->get();
            $ids = [];
            
            foreach ($task as $v) {
                # code...
                // $ids = $ids+explode(',',$v->one_ids);
                // $ids[] = explode(',',$v->one_ids);
                $ids = array_merge_recursive($ids,explode(',',$v->one_ids));
            }
            $data = $data->whereIn('id',$ids);
            // var_dump($ids);
           }
            
        }
        if(!empty($params['shop_id'])){
            $data = $data->where('shop_id',$params['shop_id']);
        }
        if(!empty($params['type'])){
            $data = $data->where('type',$params['type']);
        }
        if(!empty($params['supply_user'])){
            $data = $data->where('supply_user','like','%'.$params['supply_user'].'%');
        }
        if(!empty($params['spu'])){
            $data = $data->where('spulist','like','%'.$params['spu'].'%');
        }
        if(!empty($params['one_cate_id'])){
            $data = $data->whereIn('one_cate_id',$params['one_cate_id']);
        }
        if(!empty($params['two_cate_id'])){
            $data = $data->whereIn('two_cate_id',$params['two_cate_id']);
        }
        if(!empty($params['three_cate_id'])){
            $data = $data->whereIn('three_cate_id',$params['three_cate_id']);
        }


        $totalNum = $data->count();
        $data = $data->offset($page)->limit($limit)->orderBy('creattime','desc')->get();


        // $namearr = [];
        foreach ($data as $k=>$v) {
            //获取品类
            $one_cate = $this->GetCategory($v->one_cate_id)['name'];
            $two_cate = $this->GetCategory($v->two_cate_id)['name'];
            $three = $this->GetCategory($v->three_cate_id);
            $three_cate = $three['name'];
            $cate_user_id = $three['supervisor_id'];
            if(!empty($cate_user_id)){
                $ids = explode(",",$cate_user_id);
                $v->cate_user_id = $ids;
            }else{
                $v->cate_user_id[] = 0;
            }
            

            $data[$k]->category = $one_cate.'-'.$two_cate.'-'.$three_cate;
            # code...
            $v->account = '';
            if($v->user_id>0){
                $v->account =  $this->GetUsers($v->user_id)['account'];
            }

            $v->shop_name = '';
            if($v->shop_id>0){
                $v->shop_name =  $this->GetShop($v->shop_id)['shop_name'];
            }

            $names = '';


            $data[$k]->tag_name = '';
            $data[$k]->tag_id = 0;
            if($data[$k]->tag){
                $tag_name = DB::table('amazon_tag')->where('id',$data[$k]->tag)->first();
                if(!empty($tag_name)){
                    $data[$k]->tag_name = $tag_name->name;
                    $data[$k]->tag_id = $tag_name->id;
                }
            }

            $taskstatus = db::table('amazon_place_order_task')->where('mode',1)->where('status','>=',2)->whereRaw("find_in_set({$v->id},`one_ids`)")->first();

            if($taskstatus){
                $data[$k]->status = $taskstatus->status;
            }
        }

        return [
            'data' => $data,
            'totalNum' => $totalNum,
            'type'=>'success',
        ];

    }




     //生产下单任务详情-单人
     public function TeamPlaceOrderTaskByOneDetail($params){

        if(isset($params['id'])){
           $id = $params['id'];
        }else{
            return ['type'=>'fail','msg'=>'需要id'];
        }

        $task = DB::table('amazon_team_task_one')->where('id',$id)->first();

        $task->account = $this->GetUsers($task->user_id)['account']??'';

        $task->shop_name = $this->GetShop($task->shop_id)['shop_name']??'';

        $task->expect_date = json_decode($task->expect_date);
        $data = DB::table('amazon_team_task_detail')->where('order_id',$id)->get();


        $cate = DB::table('self_spu')->where('id',$data[0]->spu_id)->select('base_spu_id','one_cate_id','two_cate_id','three_cate_id')->first();
        $touser_id = 0;
        $account = '';
        //新品下单polo品类如果是纯色的加上陈显爱为默认审核人，印花加上林妮燕为默认审核人
        if($task->type==1){
            //女装-无袖-polo:416  女装-短袖-polo:33   女装-长袖-polo:34
            //男装-短袖-polo:140  男装-长袖-polo:141
            //幼童-polo:230
            //男童-polo:238
            //女童-短袖POLO:260
            //陈显爱 96  林妮燕 105
            $polos = [416,33,34,140,141,230,238,260];
            if(in_array($cate->three_cate_id,$polos)){
                $basespures = db::table('self_base_spu')->where('id',$cate->base_spu_id)->first();
                if($basespures->color_style==1){
                    //纯色
                    $touser_id = 96;
                    $account = '陈显爱';
                }else if($basespures->color_style==2){
                    //印花
                    $touser_id = 105;
                    $account = '林妮燕';
                }
            }

        }

        $task->fz_account =  $account;
        $task->fz_user_id = $touser_id;


        foreach ($data as $v) {
            if($task->type==2){
                $v->day_order = 0;
                $cus = Db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
                if(empty($cus)){
                    return [
                        'type' => 'fail',
                        'msg' => '系统没有'.$v->custom_sku.'的数据'
                    ];
                }
                if($cus->old_custom_sku){
                    $v->custom_sku = $cus->old_custom_sku;
                }
                $v->img = $this->GetCustomskuImg($v->custom_sku);
                //获取fba库存
                $sku = Db::table('self_sku')->where('custom_sku_id',$cus->id)->where('shop_id',$task->shop_id)->select('sku','id','old_sku')->first();
                $v->fba_inventory = 0;
                $v->lastmonth_salesale = 0;
                $v->thismonth_sale = 0;
                $v->return_rate  = 0;

                // if(empty($sku)){
                //     $here_res = $this->getHereInventory([$v->custom_sku],'custom_sku');
                // }
        
                if(!empty($sku)){
                    $sku = json_decode(json_encode($sku),true);
                    if($sku['old_sku']){
                        $skulist = $sku['old_sku'];
                    }else{
                        $skulist = $sku['sku'];
                    }
                    $fba_res = $this->getFbaInventory([$skulist],'sku');
                    if($fba_res){
                        foreach ($fba_res as $inven){
                            $v->fba_inventory += $inven['in_stock_num']+$inven['in_bound_num']+$inven['transfer_num'];
                        }
                    }else{
                        $v->fba_inventory = 0;
                    }
                    //前五月退货数量
                    $s_5_start = date('Y-m-d',strtotime("-150 day"));
                    $s_5_end = date('Y-m-d',time());
                    $return_num = db::table('amazon_return_order')->where('sku_id',$sku['id'])->whereBetween('beijing_date', [$s_5_start, $s_5_end])->sum('quantity');
    
                    $v->history_order = $this->GetOrderPlaceOrderBySku($sku['id'],$task->shop_id);

                    //五月销量
                    $v->lastmonth_salesale =  $v->history_order['a150']['order'];
                    //当月销量
                    $v->thismonth_sale = $v->history_order['this_moon']['order'];

                    if($v->history_order['a150']['order']>0&&$return_num){
                        $v->return_rate  = round(($return_num/$v->history_order['a150']['order'])*100,2);
                    }

                    if($v->history_order['a14']['order']>0){
                        $v->day_order = round($v->history_order['a14']['order']/14,2);
                    }

                    $v->fba_inventory_day = 0;
                    if($v->day_order>0&&$v->fba_inventory>0){
                        $v->fba_inventory_day = ceil($v->fba_inventory/$v->day_order);
                    }

                    
                
                    
                    // if($return_num>0&&$lastmonth_sales>0){
                    //     $v->return_rate  = round(($return_num/$lastmonth_sales)*100,2);
                    // }
                    $v->sku_id = $sku['id'];
//                     //获取月销量和历史5个月销量
//                     $month = date('m');
//                     $start_time = date('Y-m-01 00:00:00');
//                     $end_time = date('Y-m-01 00:00:00',strtotime("+1 months"));
//                     $monthsales = Db::table('amazon_order_item')->where('seller_sku',$skulist)->where('shop_id',$task->shop_id)->where('order_status','!=','Canceled')->whereBetween('amazon_time', [$start_time, $end_time])->select('quantity_ordered')->get();
// //               var_dump($skulist);
// //                var_dump($monthsales);
//                     if(!empty($monthsales)){
//                         $monthsales = json_decode(json_encode($monthsales),true);
//                         $this_month = array_column($monthsales,'quantity_ordered');
//                         $v->thismonth_sale = array_sum($this_month);
//                     }else{
//                         $v->thismonth_sale = 0;
//                     }
//                     $lastmonth = $month-5;
//                     if($lastmonth<0){
//                         $year = date('Y',strtotime("-1 year"));
//                         $lastmonth = 12+$lastmonth;
//                     }elseif($lastmonth==0){
//                         $year = date('Y',strtotime("-1 year"));
//                         $lastmonth = 12;
//                     }else{
//                         $year = date('Y');
//                     }
// //                    if($lastmonth<10){
// //                        $lastmonth = '0'.$lastmonth;
// //                    }
//                     //历史5个月销量
//                     // $lastmonth_sales = false;
//                     $lastmonth_sales = $this->getMonthSales($skulist,$task->shop_id,$lastmonth,$year);
//                     if($lastmonth_sales){
//                         $v->lastmonth_salesale = $lastmonth_sales;
//                     }else{
//                         $v->lastmonth_salesale = 0;
//                     }


//                     $r_start_time = date($year.'-'.$month.'-01 00:00:00');
//                     $r_start_int = strtotime($r_start_time);
//                     $r_end_int = strtotime("+5 months",$r_start_int);
//                     $r_end_time = date('Y-m-d H:i:s',$r_end_int);
//                     //前五月退货数量
//                     $return_num = db::table('amazon_return_order')->where('sku_id',$sku['id'])->whereBetween('beijing_date', [$r_start_time, $r_end_time])->sum('quantity');
    
//                     if($return_num>0&&$lastmonth_sales>0){
//                         $v->return_rate  = round(($return_num/$lastmonth_sales)*100,2);
//                     }


                }

                $v->custom_sku_price = $this->GetCustomSkuPrice($v->custom_sku);

                //本地仓库存
                $tongan = 0;
                $quanzhou = 0;
                $cloud = $cus->cloud_num;
                // $here_res = false;
                $here_res = $this->getHereInventory([$v->custom_sku],'custom_sku');
                if(!empty($here_res)){
                    if($here_res['tongan']){
                        $tongan = $here_res['tongan'][$v->custom_sku];
                    }
                    if($here_res['quanzhou']){
                        $quanzhou = $here_res['quanzhou'][$v->custom_sku];
                    }
                }
                $v->here_inventory_day = 0;
                $v->here_inventory = $tongan+$quanzhou+$cloud;

                if($v->day_order>0&&$v->here_inventory>0){
                    $v->here_inventory_day = ceil($v->here_inventory/$v->day_order);
                }
//            }
                //如果是欧码，需要查询美码
                if($task->sales_market==2){
                    $v->us_inventory = 0;
                    $v->us_custom_sku = '';
                    $base_spu_id = $this->GetBaseSpuIdBySpu($v->spu);
                    $us_spu = db::table('self_spu')->where('base_spu_id',$base_spu_id)->where('market','U')->first();
                    if($us_spu){
                        $us_cus = db::table('self_custom_sku')->where('spu_id',$us_spu->id)->where('color',$cus->color)->where('size',$cus->size)->first();
                        if($us_cus){
                            $us_here_res = $this->getHereInventory([$us_cus->custom_sku],'custom_sku');
                            if(!empty($us_here_res)){
                                if($us_here_res['tongan']){
                                    $us_tongan = $us_here_res['tongan'][$us_cus->custom_sku];
                                }
                                if($us_here_res['quanzhou']){
                                    $us_quanzhou = $us_here_res['quanzhou'][$us_cus->custom_sku];
                                }
                            }
                            $v->us_custom_sku = $us_cus->custom_sku;
                            $v->us_inventory = $us_tongan+$us_quanzhou+$us_cus->cloud_num;
                        }
                     
                    }

                }
            }

            $v->order_num = json_decode($v->order_num);
            $v->spu = $this->GetOldSpu($v->spu);
            $v->img = $this->GetCustomskuImg($v->custom_sku);
            # code...
        }
        $tag = '';
        if($task->tag){
            $tag_name = DB::table('amazon_tag')->where('id',$task->tag)->first();
            if(!empty($tag_name)){
                $tag = $tag_name->name;
            }
        }

        $task->tag_name = $tag;

        return [
            'detail' => $data,
            'order'=>$task,
            'type' => 'success',
        ];

    }




    //生产下单任务-集体提交界面
    public function TeamPlaceOrderTaskByData($params){

        // $day = date("l");
        // if($day!=2){
        //     return [
        //         'type' => 'fail',
        //         'msg' => '非合并日!无法合并!请在周二汇总数据!'
        //     ];
        // }

        $ids = $params['ids'];

        $detail = DB::table('amazon_team_task_detail')->whereIn('order_id',$ids)->orderby('spu')->orderby('color_name_en')->get();

        $max =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->Max('batch');

        $new_data = [];

        foreach ($detail as $v) {
            # code...
            $num = json_decode($v->order_num);
         
            for ($i=0; $i <$max ; $i++) { 
                # code...
                if(isset($num[$i])){
                    $order = $num[$i];
                }else{
                    $order = 0;
                }
                if(isset($new_data[$v->custom_sku]['order_num'][$i])){

                    $new_data[$v->custom_sku]['order_num'][$i] +=(int)$order;
                }else{
                    $new_data[$v->custom_sku]['order_num'][$i] = (int)$order;
                }
            }
            $new_data[$v->custom_sku]['custom_sku_id'] = $v->custom_sku_id;
            $new_data[$v->custom_sku]['custom_sku'] = $v->custom_sku;
            $new_data[$v->custom_sku]['spu']  = $this->GetOldSpu($v->spu);
            $new_data[$v->custom_sku]['color_name_en'] = $v->color_name_en;
            $new_data[$v->custom_sku]['size'] = $v->size;
            $new_data[$v->custom_sku]['name_en'] = $v->name_en;
            $new_data[$v->custom_sku]['img'] = $this->GetCustomskuImg($v->custom_sku);

        }
        
        $new_data = array_values($new_data);


        $users =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->get();

        $head = [];
        foreach ($users as $v) {
            # code...
            $account = $this->GetUsers($v->user_id)['account'];
            if($v->type==1){
                $type = '新品';
            }else{
                $type = '旧品翻单';
            }
            if($v->sales_market==1){
                $sales_market = '美国';
            }else if($v->sales_market==2){
                $sales_market = '欧洲';
            }else if($v->sales_market==3){
                $sales_market = '日本';
            }

            $expect_date = implode(',',json_decode($v->expect_date));

            $shop = $this->GetShop($v->shop_id)['shop_name'];

            if($v->sale_crowd==1){
                $sale_crowd = '成年男性';
            }else if($v->sale_crowd==2){
                $sale_crowd = '成年女性';
            }else if($v->sale_crowd==3){
                $sale_crowd = '中大童';
            }else if($v->sale_crowd==4){
                $sale_crowd = '幼童';
            }

            if($v->is_optimization==1){
                $is_optimization = '是';
            }else{
                $is_optimization = '否';
            }


            $tag = '';
            if($v->tag){
                $tag_name = DB::table('amazon_tag')->where('id',$v->tag)->first();
                if(!empty($tag_name)){
                    $tag = $tag_name->name;
                }
            }

            $msg['content'] = $v->content;
            $msg['account'] = $account;
            $msg['tag'] = $tag;
            $msg['type'] = $type;
            $msg['sales_market'] = $sales_market;
            $msg['expect_date'] = $expect_date;
            $msg['shop'] = $shop;
            $msg['sale_crowd'] = $sale_crowd;
            $msg['is_optimization'] = $is_optimization;
            // $msg = '运营：'.$account.'吊牌：'.$tag.' 是否新品：'.$type.' 销售市场：'.$sales_market.' 期望交期：'.$expect_date.' 店铺：'.$shop.' 销售人群：'.$sale_crowd.' 是否优化尺寸：'.$is_optimization;
            $head[] = $msg;
        }
        return['type'=>'success','detail'=>$new_data,'head_title'=>$head];
    }

    //生产下单任务-集体下单
    public function TeamPlaceOrderTaskByTotal($params){


       $ids = $params['ids'];
       $user_id = $params['user_id'];
       if(empty($ids)){
           return['type'=>'fail','msg'=>'缺少id'];
       }

       $taskone =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->first();
       $detail = DB::table('amazon_team_task_detail')->whereIn('order_id',$ids)->orderby('spu')->orderby('color_name_en')->get();

       $spulist = [];
       $skulist = [];
       $order_num = 0;
       $spu_cate = '';
      
       $spunum = [];
       foreach ($detail as $v) {
        # code...
        
            $spulist[$v->spu] = $v->spu;
            $skulist[$v->custom_sku] = $v->custom_sku;
            $order = 0;
            $num = json_decode($v->order_num);
            foreach ($num as $nv) {
                # code...
                $order+=$nv;
            }


            $order_num +=$order;

            $spus = $this->GetSpu($v->spu_id);


            $cusres = $this->GetCustomSkus($v->custom_sku);

            $color_id =  $cusres['color_id'];


            $spunum[$v->spu_id.$color_id]['spu_id'] = $v->spu_id;
            $spunum[$v->spu_id.$color_id]['color_id']=$color_id;
            if(isset($spunum[$v->spu_id.$color_id]['order'])){
                $spunum[$v->spu_id.$color_id]['order'] += $order;
            }else{
                $spunum[$v->spu_id.$color_id]['order'] = $order;
            }
           


            $is_ban = db::table('self_spu_color_isplace')->where('spu_id',$v->spu_id)->where('color_id',$color_id)->first();
            if($is_ban){
                return [
                    'type' => 'fail',
                    'msg' =>  'spu+颜色已被禁用'.$v->custom_sku
                ];
            }
            $cates = $spus['one_cate_id'].'-'.$spus['two_cate_id'].'-'.$spus['three_cate_id'];

            $cate_user_ids = $this->GetCategory($spus['three_cate_id'])['supervisor_id'];
            if(!empty($cate_user_ids)){
                $idss = explode(",",$cate_user_ids);
                if(!in_array($user_id,$idss)){
                    return [
                        'type' => 'fail',
                        'msg' =>  '非品类负责人，无法下单'
                    ];
                }
            }else{
                return [
                    'type' => 'fail',
                    'msg' =>  '此品类无负责人，无法下单'
                ];
            }



            if(empty($spu_cate)){
                $spu_cate = $cates;
            }else{
                if($cates!=$spu_cate){
                    return [
                        'type' => 'fail',
                        'msg' =>  '同一品类的库存sku才能下单，请删除此库存sku后重试.'.$v->custom_sku.'子订单号：'.$v->order_id
                    ];
                }
            }
       }




       foreach ($spunum as $sspu => $snum) {
            # code...
            $spures = db::table('self_spu')->where('id',$sspu)->first();
            $basees = db::table('self_spu_color')->where('base_spu_id',$snum['spu_id'])->where('color_id',$snum['color_id'])->first();
            if($basees){
                $order_start_quantity = $basees->order_start_quantity;
                if($order_start_quantity!=0){
                    if($snum['order']%$order_start_quantity!=0){
                        return [
                            'type' => 'fail',
                            'msg' =>  '该spu下单数量非下单起订量或下单起订量的倍数，请重新下单'.$spures->spu.'起订量：'.$order_start_quantity.'当前量:'.$snum['order']
                        ];
                    }
                }
            }
           
       
        }




        $supply_user = $params['supply_user'];

        $add['one_ids'] = implode(',',$ids);
        $add['user_id'] = $user_id;
        $add['creattime'] = date('Y-m-d H:i:s',time());
        $add['status'] = 0;
        $add['content'] = $params['content']??'';
        $add['supply_user'] = implode(',',$supply_user);
        $add['one_cate_id'] = $taskone->one_cate_id;
        $add['two_cate_id'] = $taskone->two_cate_id;
        $add['three_cate_id'] = $taskone->three_cate_id;
        $spulist = array_values($spulist);
        $add['spulist'] = implode(',',$spulist);
        $add['sku_count'] = count($skulist);
        $add['order_num'] = $order_num;
        $add['mode'] = 1;
        $add['type'] = $taskone->type;
        $task_id = Db::table('amazon_place_order_task')->insertGetId($add);

        if($task_id){
            foreach ($params['ids'] as $id) {
                # code...
                DB::table('amazon_team_task_one')->where('id',$id)->update(['status'=>1]);
            }


            foreach ($detail as $v) {
                # code...
                $detail_add['spu'] = $this->GetOldSpu($v->spu);
                $detail_add['custom_sku'] = $v->custom_sku;
                $detail_add['size'] = $v->size;
                $detail_add['color_name'] = $v->color_name;
                $detail_add['color_name_en'] = $v->color_name_en;
                $detail_add['order_num'] = $v->order_num;
                $detail_add['order_id'] =  $task_id;
                $detail_add['name_en'] = $v->name_en;
                $detail_add['spu_id'] = $v->spu_id;
                $detail_add['custom_sku_id'] = $v->custom_sku_id;
                Db::table('amazon_place_order_detail')->insert($detail_add);
            }
        }



        $cate = DB::table('self_spu')->where('id',$detail[0]->spu_id)->select('base_spu_id','one_cate_id','two_cate_id','three_cate_id')->first();
        $touser_id = 0;
        $account = '';
        //新品下单polo品类如果是纯色的加上陈显爱为默认审核人，印花加上林妮燕为默认审核人
        if($taskone->type ==1){
            //女装-无袖-polo:416  女装-短袖-polo:33   女装-长袖-polo:34
            //男装-短袖-polo:140  男装-长袖-polo:141
            //幼童-polo:230
            //男童-polo:238
            //女童-短袖POLO:260
            //陈显爱 96  林妮燕 105
            $polos = [416,33,34,140,141,230,238,260];
            if(in_array($cate->three_cate_id,$polos)){
                $basespures = db::table('self_base_spu')->where('id',$cate->base_spu_id)->first();
                if($basespures->color_style==1){
                    //纯色
                    $touser_id = 96;
                    $account = '陈显爱';
                }else if($basespures->color_style==2){
                    //印花
                    $touser_id = 105;
                    $account = '林妮燕';
                }
            }

        }

        $return['account'] = $account;
        $return['user_id'] = $touser_id;
        $return['link'] = '/collective_order_data?list_type=1&order_id='.$task_id;
        $return['order_id'] = $task_id;

        return['type'=>'success','data'=>$return];
    }




    public function TeamPlaceOrderGetCusUser($params){
        $key = $params['key'];
        $ids = $params['ids'];
        $custom_sku_id = $params['custom_sku_id'];
        $detail = DB::table('amazon_team_task_detail as a')->leftjoin('amazon_team_task_one as b','a.order_id','=','b.id')
        ->whereIn('order_id',$ids)
        ->where('custom_sku_id', $custom_sku_id)
        ->select('a.id','a.order_num','b.user_id','a.order_id')
        ->get();
        $new_data = [];
        $i = 0;
        
        foreach ($detail as $v) {
            # code...
            $order = json_decode($v->order_num);
          
            if(isset($order[$key])){
                $new_data[$i]['user_id'] = $v->user_id;
                $new_data[$i]['account'] = $this->GetUsers($v->user_id)['account'];
                $new_data[$i]['order_num'] = (int)$order[$key];
                $new_data[$i]['id'] = $v->id;
                $new_data[$i]['order_id'] = 'Z-'.$v->order_id;
                $i++;
            }
        }

        return['type'=>'success','data'=>$new_data,'detail'=> $detail];
    }


    public function TeamPlaceOrderUpdateCusUser($params){

        $data = $params['data'];

        foreach ($data as $v) {
            # code...
            $key = $v['key'];
            $id = $v['id'];
            $num = $v['num'];
            $detail = DB::table('amazon_team_task_detail')->where('id',$id)->first();
            $order = json_decode($detail->order_num);
            if(isset($order[$key])){
                $order[$key] = $num;
            }else{
                return['type'=>'fail','msg'=>'修改失败，此用户无此批号id-'.$id];
            }
            DB::table('amazon_team_task_detail')->where('id',$id)->update(['order_num'=>json_encode($order)]);

            //修改总信息
            $order_id =  $detail->order_id;
            $list = DB::table('amazon_team_task_detail')->where('order_id',$order_id)->get();
            $order_num = 0;
            $skus = [];
            foreach ($list as $v) {
                # code...
                $order = json_decode($v->order_num,true);
                $od = 0;
                foreach ($order as $ov) {
                    # code...
                    $od+= $ov;
                }

                $order_num+=$od;
                $skus[$v->custom_sku_id] = 1;
            }
            $sku_count = count($skus);

            $update['sku_count'] = $sku_count;
            $update['order_num'] = $order_num;
            DB::table('amazon_team_task_one')->where('id',$order_id)->update($update);
        }


        return['type'=>'success','msg'=>'修改成功'];
    }



    public function  TeamPlaceOrderDelCusUser($params){
        $ids = $params['id'];
        DB::table('amazon_team_task_detail')->whereIn('id',$ids)->delete();
        return['type'=>'success','msg'=>'删除成功'];
    }
    //  //生产下单任务列表-集体
    //  public function TeamPlaceOrderTaskByTotalList($params){

    //     $pagenum = isset($params['page']) ? $params['page'] : 1;
    //     $limit = isset($params['limit']) ? $params['limit'] : 30;

    //     $page  =  $pagenum- 1;
    //     if($page!=0){
    //         $page  =  $page * $limit;
    //     }

    //     $data = DB::table('amazon_team_task_total');

    //     if(isset($params['user_id'])){
    //         $data = $data->where('user_id',$params['user_id']);
    //     }
    //     if(!empty($params['status'])){
    //         $data = $data->whereIn('status',$params['status']);
    //     }
      
    //     if(!empty($params['supply_user'])){
    //         $data = $data->where('supply_user','like','%'.$params['supply_user'].'%');
    //     }

    //     $totalNum = $data->count();
    //     $data = $data->offset($page)->limit($limit)->orderBy('creattime','desc')->get();


    //     // $namearr = [];
    //     foreach ($data as $k=>$v) {
    //         //获取品类
    //         $one_cate = $this->GetCategory($v->one_cate_id)['name'];
    //         $two_cate = $this->GetCategory($v->two_cate_id)['name'];
    //         $three_cate = $this->GetCategory($v->three_cate_id)['name'];
    //         $data[$k]->category = $one_cate.'-'.$two_cate.'-'.$three_cate;
    //         # code...
    //         $v->account = '';
    //         if($v->user_id>0){
    //             $v->account =  $this->GetUsers($v->user_id)['account'];
    //         }
    //     }

    //     return [
    //         'type'=>'success',
    //         'data' => $data,
    //         'totalNum' => $totalNum,
    //     ];

    // }



    public function TeamPlaceOrderTaskByTotalDetail($params){

        if(isset($params['task_id'])){
           $task_id = $params['task_id'];
        }else{
            return['type'=>'fail','msg'=>'缺少id'];
        }

        $system_task = DB::table('tasks')->where('ext','like','%order_id='.$task_id.'%')->select('Id')->first();
        if(!empty($system_task)){
            $taskId = $system_task->Id;
        }else{
            $taskId = 0;
        }
        $tasks = DB::table('amazon_place_order_task')->where('id',$task_id)->first();
        if($tasks){
            $ids = explode(',',$tasks->one_ids);
        }else{
            return['type'=>'fail','msg'=>'无此任务'];
        }
  

        $tasks->account = $this->GetUsers($tasks->user_id)['account']??'';
        $tasks->shop_name = $this->GetShop($tasks->shop_id)['shop_name']??''; 
        $tasks->supply_user_name = $this->GetUsers($tasks->supply_user)['account']??'';

        $tasks->yj_saletime = '';


        $task = DB::table('tasks')->where('ext','like',"%{$task_id}%")->select('Id','desc','ext')->first();
        if($task){
            $ext = json_decode($task->ext,true);
            if(isset($ext['start_time'])&&isset($ext['end_time'])){
                $tasks->yj_saletime = $ext['start_time'].'~'.$ext['end_time'];
            }
    
        }



        $detail = DB::table('amazon_team_task_detail as a')->leftjoin('amazon_team_task_one as b','a.order_id','=','b.id')->whereIn('order_id',$ids)->select('a.*','b.shop_id','b.sales_market')->get();


        $cate = DB::table('self_spu')->where('id',$detail[0]->spu_id)->select('base_spu_id','one_cate_id','two_cate_id','three_cate_id')->first();
        $touser_id = 0;
        $account = '';
        //新品下单polo品类如果是纯色的加上陈显爱为默认审核人，印花加上林妮燕为默认审核人
        if($tasks->type==1){
            //女装-无袖-polo:416  女装-短袖-polo:33   女装-长袖-polo:34
            //男装-短袖-polo:140  男装-长袖-polo:141
            //幼童-polo:230
            //男童-polo:238
            //女童-短袖POLO:260
            //陈显爱 96  林妮燕 105
            $polos = [416,33,34,140,141,230,238,260];
            if(in_array($cate->three_cate_id,$polos)){
                $basespures = db::table('self_base_spu')->where('id',$cate->base_spu_id)->first();
                if($basespures->color_style==1){
                    //纯色
                    $touser_id = 96;
                    $account = '陈显爱';
                }else if($basespures->color_style==2){
                    //印花
                    $touser_id = 105;
                    $account = '林妮燕';
                }
            }

        }

        $tasks->fz_account =  $account;
        $tasks->fz_user_id = $touser_id;


        $max =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->Max('batch');

        $new_data = [];

        foreach ($detail as $v) {
            # code...
            $num = json_decode($v->order_num);
         
            for ($i=0; $i <$max ; $i++) { 
                # code...
                if(isset($num[$i])){
                    $order = $num[$i];
                }else{
                    $order = 0;
                }
                if(isset($new_data[$v->custom_sku]['order_num'][$i])){

                    $new_data[$v->custom_sku]['order_num'][$i] +=(int)$order;
                }else{
                    $new_data[$v->custom_sku]['order_num'][$i] = (int)$order;
                }
            }
            $new_data[$v->custom_sku]['task_id'] = $v->order_id;
            $new_data[$v->custom_sku]['custom_sku'] = $v->custom_sku;
            $new_data[$v->custom_sku]['custom_sku_id'] = $v->custom_sku_id;
            $new_data[$v->custom_sku]['spu'] =  $this->GetOldSpu($v->spu);
            $new_data[$v->custom_sku]['color_name_en'] = $v->color_name_en;
            $new_data[$v->custom_sku]['color_name'] = $v->color_name;
            $new_data[$v->custom_sku]['size'] = $v->size;
            $new_data[$v->custom_sku]['name_en'] = $v->name_en;
            $new_data[$v->custom_sku]['img'] = $this->GetCustomskuImg($v->custom_sku);


            //获取fba库存
            $sku = Db::table('self_sku')->where('custom_sku_id',$v->custom_sku_id)->where('shop_id',$v->shop_id)->select('sku','id','old_sku')->first();
            $new_data[$v->custom_sku]['fba_inventory'] = 0;
            $new_data[$v->custom_sku]['lastmonth_salesale'] = 0;
            $new_data[$v->custom_sku]['thismonth_sale'] = 0;
            $new_data[$v->custom_sku]['return_rate'] = 0;
            $new_data[$v->custom_sku]['day_order'] = 0;
            if(!empty($sku)){
                $sku = json_decode(json_encode($sku),true);
                if($sku['old_sku']){
                    $skulist = $sku['old_sku'];
                }else{
                    $skulist = $sku['sku'];
                }
                $fba_res = $this->getFbaInventory([$skulist],'sku');
                if($fba_res){
                    foreach ($fba_res as $inven){
                        $new_data[$v->custom_sku]['fba_inventory'] += $inven['in_stock_num']+$inven['in_bound_num']+$inven['transfer_num'];
                    }
                }else{
                    $new_data[$v->custom_sku]['fba_inventory'] = 0;
                }

                //前五月退货数量
                $s_5_start = date('Y-m-d',strtotime("-150 day"));
                $s_5_end = date('Y-m-d',time());

                $return_num = db::table('amazon_return_order')->where('sku_id',$sku['id'])->whereBetween('beijing_date', [$s_5_start, $s_5_end])->sum('quantity');

                $new_data[$v->custom_sku]['history_order'] = $this->GetOrderPlaceOrderBySku($sku['id'],$v->shop_id);

                //五月销量
                $new_data[$v->custom_sku]['lastmonth_salesale'] =  $new_data[$v->custom_sku]['history_order']['a150']['order'];
                //当月销量
                $new_data[$v->custom_sku]['thismonth_sale'] = $new_data[$v->custom_sku]['history_order']['this_moon']['order'];

                if($new_data[$v->custom_sku]['history_order']['a150']['order']>0&&$return_num>0){
                    $order_150 = $new_data[$v->custom_sku]['history_order']['a150']['order'];
                    $new_data[$v->custom_sku]['return_num'] = $return_num;
                    $new_data[$v->custom_sku]['return_order'] = $order_150;
                    $new_data[$v->custom_sku]['return_rate']  = round(($return_num/$order_150)*100,2);
                }

                if($new_data[$v->custom_sku]['history_order']['a14']['order']>0){
                    $t_order = $new_data[$v->custom_sku]['history_order']['a14']['order'];
                    $new_data[$v->custom_sku]['day_order'] = round($t_order/14,2);
                }

                $new_data[$v->custom_sku]['fba_inventory_day'] = 0;
                if($new_data[$v->custom_sku]['day_order']>0&&$new_data[$v->custom_sku]['fba_inventory']>0){
                    $new_data[$v->custom_sku]['fba_inventory_day'] = ceil($new_data[$v->custom_sku]['fba_inventory']/$new_data[$v->custom_sku]['day_order']);
                }
                $new_data[$v->custom_sku]['sku_id'] = $sku['id'];
                

            }

            //本地仓库存
            $tongan = 0;
            $quanzhou = 0;
            $cus = Db::table('self_custom_sku')->where('id',$v->custom_sku_id)->first();
            $cloud  = 0;
            if($cus){
                $cloud = $cus->cloud_num;
            }

            $here_res = $this->getHereInventory([$v->custom_sku],'custom_sku');
            if(!empty($here_res)){
                if($here_res['tongan']){
                    $tongan = $here_res['tongan'][$v->custom_sku];
                }
                if($here_res['quanzhou']){
                    $quanzhou = $here_res['quanzhou'][$v->custom_sku];
                }
            }

            $new_data[$v->custom_sku]['custom_sku_price'] = $this->GetCustomSkuPrice($v->custom_sku);
            $new_data[$v->custom_sku]['here_inventory']= $tongan+$quanzhou+$cloud;
            $new_data[$v->custom_sku]['here_inventory_day'] = 0;
            if($new_data[$v->custom_sku]['here_inventory']>0&&$new_data[$v->custom_sku]['day_order']>0){
                $new_data[$v->custom_sku]['here_inventory_day'] = ceil($new_data[$v->custom_sku]['here_inventory']/$new_data[$v->custom_sku]['day_order']);
            }
//            }
           
              //如果是欧码，需要查询美码
              if($v->sales_market==2){
                $new_data[$v->custom_sku]['us_inventory'] = 0;
                $new_data[$v->custom_sku]['us_custom_sku'] = '';
                $base_spu_id = $this->GetBaseSpuIdBySpu($v->spu);
                $us_spu = db::table('self_spu')->where('base_spu_id',$base_spu_id)->where('market','U')->first();
                if($us_spu){
                    $us_cus = db::table('self_custom_sku')->where('spu_id',$us_spu->id)->where('color',$cus->color)->where('size',$cus->size)->first();
                    if($us_cus){
                        $us_here_res = $this->getHereInventory([$us_cus->custom_sku],'custom_sku');
                        if(!empty($us_here_res)){
                            if($us_here_res['tongan']){
                                $us_tongan = $us_here_res['tongan'][$us_cus->custom_sku];
                            }
                            if($us_here_res['quanzhou']){
                                $us_quanzhou = $us_here_res['quanzhou'][$us_cus->custom_sku];
                            }
                        }
                        $new_data[$v->custom_sku]['us_custom_sku'] = $us_cus->custom_sku;
                        $new_data[$v->custom_sku]['us_inventory'] = $us_tongan+$us_quanzhou+$us_cus->cloud_num;
                    }
                
                }

              }


        }
        $new_data = array_values($new_data);



        $users =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->get();

        $head = [];
        $heads = [];
        foreach ($users as $v) {
            # code...
            $account = $this->GetUsers($v->user_id)['account'];
            if($v->type==1){
                $type = '新品';
            }else{
                $type = '旧品翻单';
            }
            if($v->sales_market==1){
                $sales_market = '美国';
            }else if($v->sales_market==2){
                $sales_market = '欧洲';
            }else if($v->sales_market==3){
                $sales_market = '日本';
            }

            $expect_date = implode(',',json_decode($v->expect_date));

            $shop = $this->GetShop($v->shop_id)['shop_name'];

            if($v->sale_crowd==1){
                $sale_crowd = '成年男性';
            }else if($v->sale_crowd==2){
                $sale_crowd = '成年女性';
            }else if($v->sale_crowd==3){
                $sale_crowd = '中大童';
            }else if($v->sale_crowd==4){
                $sale_crowd = '幼童';
            }

            if($v->is_optimization==1){
                $is_optimization = '是';
            }else{
                $is_optimization = '否';
            }

            $tag = '';
            if($v->tag){
                $tag_name = DB::table('amazon_tag')->where('id',$v->tag)->first();
                if(!empty($tag_name)){
                    $tag = $tag_name->name;
                }
            }
            $msg['content'] = $v->content;
            $msg['account'] = $account;
            $msg['tag'] = $tag;
            $msg['type'] = $type;
            $msg['sales_market'] = $sales_market;
            $msg['expect_date'] = $expect_date;
            $msg['shop'] = $shop;
            $msg['sale_crowd'] = $sale_crowd;
            $msg['is_optimization'] = $is_optimization;
            $msgs = '运营：'.$account.'吊牌：'.$tag.' 是否新品：'.$type.' 销售市场：'.$sales_market.' 期望交期：'.$expect_date.' 店铺：'.$shop.' 销售人群：'.$sale_crowd.' 是否优化尺寸：'.$is_optimization.' 备注：'.$v->content;
            $head[] = $msg;
            $heads[]['spu'] = $msgs;
        }


        $return['link'] = '/collective_order_data?list_type=1&order_id='.$task_id;
        $return['order_id'] = $task_id;


        $posttype = $params['posttype']??1;
        if($posttype==2){
                  
            $p['title']='汇总下单表-'.$task_id.'-'.time();

            $listtlt1 = [
                'task_id'=>'任务ID',
                'spu'=>'spu',
                'custom_sku'=>'库存sku',
                'img'=>'图片',
                'color_name'=>'颜色',
                'size'=>'尺码',
                'name_en'=>'英文品名',
            ];

            $postdata = [];
            foreach ($new_data as &$v) {
                # code...
                $order = $v['order_num'];
                foreach ($order as $ok => $ov) {
                    # code...
                    $key = 'order_'.$ok;
                    $v[$key] = $ov;
                }
                $postdata[] = $v;
            }



            $listtlt2 = [];
            for ($i=0; $i < $max; $i++) { 
                # code...
                $key = 'order_'.$i;
                $num = $i+1;
                $pc = '第'.$num.'批';
                $listtlt2[$key] = $pc;
            }

            
    
            $p['title_list']  = $listtlt1+$listtlt2;
            $p['data'] = array_merge($postdata,$heads);
            $find_user_id = $params['find_user_id']??1;
            $p['user_id'] = $find_user_id;
            $p['type'] = '汇总下单表-导出';

            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->ExcelSku($list);
        }else if($posttype==3){
            $find_user_id = $params['find_user_id']??1;
           $task3 =  $this->orderexporta($task_id,$find_user_id);
           if($task3){
            return ['type' => 'success','msg' => '加入队列成功'];
           }else{
            return ['type' => 'fail', 'msg' => '加入队列失败'];
           }
        }else if($posttype==4){
            $find_user_id = $params['find_user_id']??1;
           $task3 =  $this->orderexportb($task_id,$find_user_id);
           if($task3){
            return ['type' => 'success','msg' => '加入队列成功'];
           }else{
            return ['type' => 'fail', 'msg' => '加入队列失败'];
           }
        }

        return['type'=>'success','detail'=>$new_data,'order'=>$tasks ,'head_title'=>$head,'task'=>$return,'system_task'=>$taskId];
    }
    

    public  function orderexporta($task_id,$find_user_id){
        $tasks = DB::table('amazon_place_order_task')->where('id',$task_id)->first();
        
        $ids = explode(',',$tasks->one_ids);
        $detail = DB::table('amazon_team_task_detail as a')->leftjoin('amazon_team_task_one as b','a.order_id','=','b.id')->whereIn('a.order_id',$ids)->groupby('a.custom_sku_id')->select('a.*','b.user_id')->get();

        $users =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->get();

        $user_list = [];
        foreach ($users as $v) {
            $expect_date = json_decode($v->expect_date,true);
            foreach ($expect_date as $i => $date) {
                # code...
                $key = $v->id.'_'.$v->user_id."_".$i;
                $va = $this->GetUsers($v->user_id)['account'];
                $num = $i+1;
                $va = $va.$date.'第'.$num.'批';
                $user_list[$key] = $va;
            }

            
        }


        foreach ($detail as $v) {
            # code...

            $res =  DB::table('amazon_team_task_detail as a')->leftjoin('amazon_team_task_one as b','a.order_id','=','b.id')->whereIn('a.order_id',$ids)->where('a.custom_sku_id',$v->custom_sku_id)->select('a.*','b.user_id')->get();
            
            foreach ($res as $rk => $rv) {
                # code...
                $num = json_decode($rv->order_num,true);
                       
                foreach ($user_list as $uk => $uv) {
                    if(!isset($v->$uk)){
                        $v->$uk = 0;
                    }
                    foreach ($num  as $i => $order) {
                        # code...
                        $key = $rv->order_id.'_'.$rv->user_id."_".$i;
                        if($key==$uk){
                            $v->$uk += $order;
                        }
                    }
                    
                }

            }
        

            $v->spu =  $this->GetOldSpu($v->spu);

            $v->img = $this->GetCustomskuImg($v->custom_sku);

        }

     
        $p['title']='汇总下单表3-'.$task_id.'-'.time();

        $listtlt1 = [
            'order_id'=>'任务ID',
            'spu'=>'spu',
            'custom_sku'=>'库存sku',
            'img'=>'图片',
            'color_name'=>'颜色',
            'size'=>'尺码',
            'name_en'=>'英文品名',
        ];



        $p['title_list']  = $listtlt1+$user_list;
        $p['data'] = $detail;
        $p['user_id'] = $find_user_id;
        $p['type'] = '汇总下单表3-导出';


        // var_dump($p);

        $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
        try {
            $job::runJob($p);
        } catch(\Exception $e){
            return false;
        }
        return true;

    }

    public  function orderexportb($task_id,$find_user_id){
        $tasks = DB::table('amazon_place_order_task')->where('id',$task_id)->first();
        
        $ids = explode(',',$tasks->one_ids);
        $detail = DB::table('amazon_team_task_detail')->whereIn('order_id',$ids)->get();

        $max =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->Max('batch');
        $new_data = [];

        foreach ($detail as $v) {
            # code...
            $num = json_decode($v->order_num);
         
            $row_order = 0;
            for ($i=0; $i <$max ; $i++) { 
                # code...
                $row_order +=$num[$i];
                if(isset($num[$i])){
                    $order = $num[$i];
                }else{
                    $order = 0;
                }
                $key = 'order_'.$i;
                $v->$key = $order;
            }

            $v->row_order =  $row_order;
            $user_id = db::table('amazon_team_task_one')->where('id',$v->order_id)->first()->user_id;
            $v->account = $this->GetUsers($user_id)['account']??'';
            $v->task_id = $task_id;
            $v->spu =  $this->GetOldSpu($v->spu);

            $v->img = $this->GetCustomskuImg($v->custom_sku);



            $new_data[$v->order_id][] = json_decode(json_encode($v),true);

        }

        $users =  DB::table('amazon_team_task_one')->whereIn('id',$ids)->get();

        $head = [];
        foreach ($users as $v) {
            # code...
            $account = $this->GetUsers($v->user_id)['account'];
            if($v->type==1){
                $type = '新品';
            }else{
                $type = '旧品翻单';
            }
            if($v->sales_market==1){
                $sales_market = '美国';
            }else if($v->sales_market==2){
                $sales_market = '欧洲';
            }else if($v->sales_market==3){
                $sales_market = '日本';
            }

            $expect_date = implode(',',json_decode($v->expect_date));

            $shop = $this->GetShop($v->shop_id)['shop_name'];

            if($v->sale_crowd==1){
                $sale_crowd = '成年男性';
            }else if($v->sale_crowd==2){
                $sale_crowd = '成年女性';
            }else if($v->sale_crowd==3){
                $sale_crowd = '中大童';
            }else if($v->sale_crowd==4){
                $sale_crowd = '幼童';
            }

            if($v->is_optimization==1){
                $is_optimization = '是';
            }else{
                $is_optimization = '否';
            }

            $tag = '';
            if($v->tag){
                $tag_name = DB::table('amazon_tag')->where('id',$v->tag)->first();
                if(!empty($tag_name)){
                    $tag = $tag_name->name;
                }
            }

            $msgs = '运营：'.$account.'吊牌：'.$tag.' 是否新品：'.$type.' 销售市场：'.$sales_market.' 期望交期：'.$expect_date.' 店铺：'.$shop.' 销售人群：'.$sale_crowd.' 是否优化尺寸：'.$is_optimization.' 备注：'.$v->content;
            $head[$v->id]['spu'] = $msgs;
        }


        // $new_data = array_values($new_data);

        foreach ($ids as $id) {
            # code...
            $list[] =  $head[$id];
            foreach ($new_data[$id] as $v) {
                # code...
                $list[] = $v;
            }
            // $list[$id] = array_merge($new_data[$id], $head[$id]);

        }

        $p['title']='汇总下单表2-'.$task_id.'-'.time();

        $listtlt1 = [
            'task_id'=>'任务ID',
            'img'=>'图片',
            'spu'=>'spu',
            'custom_sku'=>'库存sku',
            'color_name'=>'颜色',
            'size'=>'尺码',
            'name_en'=>'英文品名',
            'account'=>'运营',
            'row_order'=>'合计',
        ];


        $listtlt2 = [];
        for ($i=0; $i < $max; $i++) { 
            # code...
            $key = 'order_'.$i;
            $num = $i+1;
            $pc = '第'.$num.'批';
            $listtlt2[$key] = $pc;
        }

        

        $p['title_list']  = $listtlt1+$listtlt2;
        $p['data'] = $list;
        $p['user_id'] = $find_user_id;
        $p['type'] = '汇总下单表2-导出';

        // var_dump($p);

        $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
        try {
            $job::runJob($p);
        } catch(\Exception $e){
            return false;
        }
        return true;

    }

    public function PlaceOrderExport($params){
        $data = DB::table('amazon_place_order_detail');

        $task = DB::table('amazon_place_order_task');

        if(isset($params['order_id'])){
            $data = $data->where('order_id',$params['order_id']);
            $task = $task->where('id',$params['order_id']);
        }

        $totalNum = $data->count();
        $data = $data->get();
        $task = $task->first();

        if(!$task){
            return [
                'type' => 'fail',
                'msg' => '无此任务'
            ];
        }

        $task_account = '';

        if($task->user_id>0){
            $task_account =  $this->GetUsers($task->user_id)['account'];
         }
        
         $task_supply_name = '';
         if(isset($task->supply_user)){
            $users = explode(',',$task->supply_user);
            $username = [];
            foreach ($users as $v) {
                # code...
                $username[] =  $this->GetUsers($v)['account'];
            }

            $task_supply_name = implode(',',$username);
          
         }

         $task_shop_name = '';
         if($task->shop_id>0){
             $task_shop_name =  $this->GetShop($task->shop_id)['shop_name'];
         }
         

         $task_tag = $task->tag;

        $excel_data = [];

        //以spu+颜色分组
        foreach ($data as $v) {
            // $spu_one['size']= $v->size;
            // $order = json_decode($v->order_num,true);
            // $spu_one['num']= 0;
            // foreach ($order as $num) {
            //     # code...
            //     $spu_one['num']+=$num;
            // }
            // $excel_data[$v->spu.$v->color_name_en][] = $spu_one;
            $excel_data['u'.$v->custom_sku] = 1;
        }

    

        $exprot_data = [];
        $i = 0;
        foreach ($excel_data as $ek => $ev){
            //根据分组取值
            $newdata = [];
            foreach ($data as $v) {
                # code...
                // $key = $v->spu.$v->color_name_en;
                $key = 'u'.$v->custom_sku;
                $spus = $this->GetSpus($v->spu);
                if($key== $ek){
                    //创建者
                    $old_spu = Db::table('self_spu')->whereIn('spu',$spus)->first();
                    if($old_spu->old_spu){
                        $v->spu = $old_spu->old_spu;
                    }
                    //款号
                    $newdata['task_id'] = $v->order_id;
                    $newdata['spu'] = $v->spu;
                    $newdata['color_name_en'] = $v->color_name_en;
                    $newdata['color_name'] = $v->color_name;
                    $newdata['size'] = $v->size;
                    $newdata['custom_sku'] = $v->custom_sku;
                    
                    $cus = Db::table('self_custom_sku')->where('custom_sku',$v->custom_sku)->orwhere('old_custom_sku',$v->custom_sku)->first();
                    $newdata['name'] = '';
                    $newdata['price'] = 0;
                    if($cus){
                        //中文品描述
                        // $newdata['name'] = $cus->name;
                        //原采购价
                        $newdata['price'] =$cus->buy_price;
                    }
                    

                    $cate = Db::table('self_spu')->whereIn('spu',$spus)->first();
                    //大类
                    $one_cate = $this->GetCategory($cate->one_cate_id)['name']??'';
                    //三类
                    $three_cate = $this->GetCategory($cate->three_cate_id)['name']??'';

                    $newdata['name'] = $one_cate.$three_cate;

                    //销售市场
                    if($task->sales_market==1){
                        $newdata['sales_market'] = '美国';
                    }else{
                        $newdata['sales_market'] = '欧洲';
                    }
        

        
                    //期望交期
                    $expect_dates = json_decode($task->expect_date,true);
                    $expect_date = '';
                    if(is_array($expect_dates)){
                        foreach ($expect_dates as $key => $value) {
                            # code...
                            $expect_date.='第'.($key+1).'批:'.$value;
                        }
                        $newdata['expect_date'] = $expect_date;
                    }else{
                        $newdata['expect_date'] =$task->expect_date;
                    }
  
        

                    //供应链负责人
                    $newdata['supply_name'] = $task_supply_name;

                    //吊牌
                    $newdata['task_tag'] = '';
                    $task_tag_name =  Db::table('amazon_tag')->where('id',$task_tag)->first();
                    if($task_tag_name){
                        $newdata['task_tag'] = $task_tag_name->name;
                    }
                
    
                    //产品负责人
                    $product_user_id = Db::table('self_spu')->whereIn('spu', $spus)->first()->user_id;
                    $newdata['product_user'] = $this->GetUsers($product_user_id)['account'];
        
                    //运营负责人
                    $newdata['account'] = $task_account;
        
                    //店铺
        
                    $newdata['shop_name'] = $task_shop_name;
        
                    //英文品名
                    $newdata['name_en'] =  $v->name_en;

                    // $newdata['XS'] = 0;
                    // $newdata['S'] = 0;
                    // $newdata['M'] = 0;
                    // $newdata['L'] = 0;
                    // $newdata['XL'] = 0;
                    // $newdata['2XL'] = 0;
                    // $newdata['3XL'] = 0;
                    // $newdata['4XL'] = 0;
                    // $newdata['5XL'] = 0;

                    // $order_num = 0;
                    // //尺寸
                    // foreach ($ev as $evv) {
                    //     # code...
                    //     $size = $evv['size'];
                    //     $newdata[$size] = $evv['num'];
                    //     $order_num+=$evv['num'];
                    // }
        
                    //订单总数量
                    // $newdata['order_num'] = $v->order_num;

                    $newdata['img'] = $this->GetCustomskuImg($v->custom_sku);

                    $order = json_decode($v->order_num,true);

                    $order_num = count($order);
                    $order_total = 0;
                    foreach ($order as $key => $value) {
                        # code...
                        $newdata['pc_'.$key] = $value;
                        $order_total +=$value;
                    }
                    $newdata['order_total'] = $order_total;

                    // $colors = Db::table('self_color_size')->where('english_name',$v->color_name_en)->first();
                    // $imgs = Db::table('self_spu_color')->whereIn('spu',$spus)->where('color_id',$colors->id)->first();
                    // if($imgs){
                    //     $newdata['img']  = $imgs->img;
                    // }
                  

             }
            }

            $exprot_data[$i] = $newdata;
            $i++;
            
        }

        $totaldata['spu'] = '合计';
        $totaldata['name_en'] = '';
        $totaldata['color_name'] = '';
        $totaldata['color_name_en'] = '';
        $totaldata['order_total'] = $task->order_num;

        $exprot_data[$i+1] = $totaldata;

        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='生产下单表-'.rand(1,5000).'-'.$params['order_id'];
            // $p['title_list']  = [
            //     'spu'=>'款号',
            //     'name_en'=>'英文品名描述',
            //     'color_name'=>'中文颜色',
            //     'color_name_en'=>'英文颜色',
            //     'order_num'=>'总数量',
            //     'XS'=>'XS',
            //     'S'=>'S',
            //     'M'=>'M',
            //     'L'=>'L',
            //     'XL'=>'XL',
            //     '2XL'=>'2XL',
            //     '3XL'=>'3XL',
            //     '4XL'=>'4XL',
            //     '5XL'=>'5XL',
            //     'img'=>'产品图片',
            //     'sales_market'=>'销售市场',
            //     'name'=>'中文品名描述',
            //     'price'=>'原采购价',
            //     'expect_date'=>'期望交期',
            //     'supply_name'=>'供应链负责人',
            //     'product_user'=>'产品负责人',
            //     'account'=>'运营负责人',
            //     'shop_name'=>'吊牌店铺',
            // ];

            $titlea  = [
                'task_id'=>'任务ID',
                'spu'=>'款号',
                'custom_sku'=>'库存sku',
                'name_en'=>'英文品名描述',
                'color_name'=>'中文颜色',
                'color_name_en'=>'英文颜色',
            ];

            $titleb = [];
            for ($i=0; $i < $order_num; $i++) { 
                # code...
                $titleb['pc_'.$i] = '第'.($i+1).'批';
            }


            $titlec = [
                'order_total'=>'订单合计',
                'size'=>'尺寸',
                'img'=>'产品图片',
                'sales_market'=>'销售市场',
                'name'=>'中文品名描述',
                'price'=>'原采购价',
                'expect_date'=>'期望交期',
                'supply_name'=>'供应链负责人',
                'product_user'=>'产品负责人',
                'account'=>'运营负责人',
                'task_tag'=>'吊牌',
                'shop_name'=>'店铺',
            ];
            $p['title_list'] = $titlea+$titleb+$titlec;
            $p['data'] = $exprot_data;


            // foreach ($p['data'] as $v) {
            //     # code...
            //     $order_num = 0;
            //     $order = json_decode($v->order_num,true);
            //     var_dump($order);
            //     // foreach ($order as $num) {
            //     //     # code...
            //     //     // $order_num+= $num;
            //     //     echo $num;
            //     // }
            //     // $v->order_num =  $order_num;
            // }
            // var_dump($p);
            $p['user_id'] = $params['find_user_id']??1;
            $p['type'] = '生产下单详情-库存sku';
    
            $job = new ExcelTaskController();
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
            return ['type' => 'success','msg' => '加入队列成功'];
            // $this->place_excel_expord($p);
        }

        if($posttype==3){
            $res = $this->PlaceOrderExportb($params);
            return $res;
        }
        return [
            'type' => 'success',
            'data' =>  $exprot_data,
            'totalNum' => $totalNum,
        ];
    }



    public function PlaceOrderExportb($params){
        $data = DB::table('amazon_place_order_detail');

        $task = DB::table('amazon_place_order_task');

        if(isset($params['order_id'])){
            $data = $data->where('order_id',$params['order_id']);
            $task = $task->where('id',$params['order_id']);
        }

        $totalNum = $data->count();
        $data = $data->get();
        $task = $task->first();

        if(!$task){
            return [
                'type' => 'fail',
                'msg' => '无此任务'
            ];
        }

        $task_account = '';

        if($task->user_id>0){
            $task_account =  $this->GetUsers($task->user_id)['account'];
         }
        
         $task_supply_name = '';
         if(isset($task->supply_user)){
            $users = explode(',',$task->supply_user);
            $username = [];
            foreach ($users as $v) {
                # code...
                $username[] =  $this->GetUsers($v)['account'];
            }

            $task_supply_name = implode(',',$username);
          
         }

         $task_shop_name = '';
         if($task->shop_id>0){
             $task_shop_name =  $this->GetShop($task->shop_id)['shop_name'];
         }
         

         $task_tag = $task->tag;

        $excel_data = [];

        //以spu+颜色分组
        foreach ($data as $v) {
            $spu_one['size']= $v->size;
            $order = json_decode($v->order_num,true);
            $spu_one['num']= 0;
            foreach ($order as $num) {
                # code...
                $spu_one['num']+=$num;
            }
            $excel_data[$v->spu.$v->color_name_en][] = $spu_one;
        }

    

        $exprot_data = [];
        $i = 0;
        foreach ($excel_data as $ek => $ev){
            //根据分组取值
            $newdata = [];
            foreach ($data as $v) {
                # code...
                $key = $v->spu.$v->color_name_en;
                $spus = $this->GetSpus($v->spu);
                if($key== $ek){
                    //创建者
                    $old_spu = Db::table('self_spu')->whereIn('spu',$spus)->first();
                    if($old_spu->old_spu){
                        $v->spu = $old_spu->old_spu;
                    }
                    //款号
                    $newdata['task_id'] = $v->order_id;
                    $newdata['spu'] = $v->spu;
                    $newdata['color_name_en'] = $v->color_name_en;
                    $newdata['color_name'] = $v->color_name;
                    $newdata['size'] = $v->size;
                    $newdata['custom_sku'] = $v->custom_sku;
                    
                    $cus = Db::table('self_custom_sku')->where('custom_sku',$v->custom_sku)->orwhere('old_custom_sku',$v->custom_sku)->first();
                    $newdata['name'] = '';
                    $newdata['price'] = 0;
                    if($cus){
                        //中文品描述
                        // $newdata['name'] = $cus->name;
                        //原采购价
                        $newdata['price'] =$cus->buy_price;
                    }
                    

                    $cate = Db::table('self_spu')->whereIn('spu',$spus)->first();
                    //大类
                    $one_cate = $this->GetCategory($cate->one_cate_id)['name']??'';
                    //三类
                    $three_cate = $this->GetCategory($cate->three_cate_id)['name']??'';

                    $newdata['name'] = $one_cate.$three_cate;

                    //销售市场
                    if($task->sales_market==1){
                        $newdata['sales_market'] = '美国';
                    }else{
                        $newdata['sales_market'] = '欧洲';
                    }
        

        
                    //期望交期
                    $expect_dates = json_decode($task->expect_date,true);
                    $expect_date = '';
                    if(is_array($expect_dates)){
                        foreach ($expect_dates as $key => $value) {
                            # code...
                            $expect_date.='第'.($key+1).'批:'.$value;
                        }
                        $newdata['expect_date'] = $expect_date;
                    }else{
                        $newdata['expect_date'] =$task->expect_date;
                    }
  
        

                    //供应链负责人
                    $newdata['supply_name'] = $task_supply_name;

                    //吊牌
                    $newdata['task_tag'] = '';
                    $task_tag_name =  Db::table('amazon_tag')->where('id',$task_tag)->first();
                    if($task_tag_name){
                        $newdata['task_tag'] = $task_tag_name->name;
                    }
                
    
                    //产品负责人
                    $product_user_id = Db::table('self_spu')->whereIn('spu', $spus)->first()->user_id;
                    $newdata['product_user'] = $this->GetUsers($product_user_id)['account'];
        
                    //运营负责人
                    $newdata['account'] = $task_account;
        
                    //店铺
        
                    $newdata['shop_name'] = $task_shop_name;
        
                    //英文品名
                    $newdata['name_en'] =  $v->name_en;

                    $newdata['XS'] = 0;
                    $newdata['S'] = 0;
                    $newdata['M'] = 0;
                    $newdata['L'] = 0;
                    $newdata['XL'] = 0;
                    $newdata['2XL'] = 0;
                    $newdata['3XL'] = 0;
                    $newdata['4XL'] = 0;
                    $newdata['5XL'] = 0;
                    $newdata['6XL'] = 0;

                    $order_num = 0;
                    //尺寸
                    foreach ($ev as $evv) {
                        # code...
                        $size = $evv['size'];
                        $newdata[$size] = $evv['num'];
                        $order_num+=$evv['num'];
                    }
        
                    // 订单总数量
                    $newdata['order_num'] = $order_num;

                    $newdata['img'] = $this->GetCustomskuImg($v->custom_sku);
             }
            }

            $exprot_data[$i] = $newdata;
            $i++;
            
        }

        $totaldata['spu'] = '合计';
        $totaldata['name_en'] = '';
        $totaldata['color_name'] = '';
        $totaldata['color_name_en'] = '';
        $totaldata['order_num'] = $task->order_num;

        $exprot_data[$i+1] = $totaldata;


            $p['title']='生产下单表-'.rand(1,5000).'-'.$params['order_id'];
            $p['title_list']  = [
                'task_id'=>'任务ID',
                'spu'=>'款号',
                'name_en'=>'英文品名描述',
                'color_name'=>'中文颜色',
                'color_name_en'=>'英文颜色',
                'order_num'=>'总数量',
                'XS'=>'XS',
                'S'=>'S',
                'M'=>'M',
                'L'=>'L',
                'XL'=>'XL',
                '2XL'=>'2XL',
                '3XL'=>'3XL',
                '4XL'=>'4XL',
                '5XL'=>'5XL',
                '6XL'=>'6XL',
                'img'=>'产品图片',
                'sales_market'=>'销售市场',
                'name'=>'中文品名描述',
                'price'=>'原采购价',
                'expect_date'=>'期望交期',
                'supply_name'=>'供应链负责人',
                'product_user'=>'产品负责人',
                'account'=>'运营负责人',
                'shop_name'=>'吊牌店铺',
            ];


            $p['data'] = $exprot_data;


            // foreach ($p['data'] as $v) {
            //     # code...
            //     $order_num = 0;
            //     $order = json_decode($v->order_num,true);
            //     var_dump($order);
            //     // foreach ($order as $num) {
            //     //     # code...
            //     //     // $order_num+= $num;
            //     //     echo $num;
            //     // }
            //     // $v->order_num =  $order_num;
            // }
            // var_dump($p);
            $p['user_id'] = $params['find_user_id']??1;
            $p['type'] = '生产下单详情-spu颜色';
    
            $job = new ExcelTaskController();
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type' => 'fail', 'msg' => '加入队列失败'];
            }
        return ['type' => 'success','msg' => '加入队列成功'];
            // $this->place_excel_expord($p);
    }



     //excel导出 
     public function place_excel_expord($params){
         try {
             $tltle = $params['title'];
             $title_list = $params['title_list'];
             $protdata = json_decode(json_encode($params['data']), true);

             $obj = new \PHPExcel();

             $fileName = $tltle. date('Y-m-d');
             $fileType = 'xlsx';

             // 以下内容是excel文件的信息描述信息
             $obj->getProperties()->setTitle($tltle); //设置标题

             // 设置当前sheet
             $obj->setActiveSheetIndex(0);

             // 设置当前sheet的名称
             $obj->getActiveSheet()->setTitle($tltle);

             /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
             $cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF", "BG", "BH", "BI", "BJ", "BK", "BL", "BM", "BN", "BO", "BP", "BQ", "BR", "BS", "BT", "BU", "BV", "BW", "BX", "BY", "BZ", "CA", "CB", "CC", "CD", "CE", "CF", "CG", "CH", "CI", "CJ", "CK", "CL", "CM", "CN", "CO", "CP", "CQ", "CR", "CS", "CT", "CU", "CV", "CW", "CX", "CY", "CZ", "DA", "DB", "DC", "DD", "DE", "DF", "DG", "DH", "DI", "DJ");
             // 设置excel标题


             $index = 0;
             $data  = [];

             //过滤数据
             foreach ($protdata  as $pk => $onedata) {
                 //过滤数据
                 $one_new_data = [];
                 foreach ($title_list as $k =>$v) {
                     foreach ($onedata as $key => $value) {
                         # code...

                         if($k!=''&&$k==$key){
                             $one_new_data[$k] = $value;
                         }
                     }
                 }
                 $data[$pk]= $one_new_data;
                 # code...
             }

             // 填充第一行数据
             foreach ($title_list as $k =>$v) {
                 $obj->getActiveSheet()->setCellValue($cellName[$index] . '1', $v);
                 $index++;
             }

             $i=0;
             // 填充第n(n>=2, n∈N*)行数据
             foreach ($data as $v) {
                 $si = 0;
                 foreach ($v as $sk => $sv) {
                     # code...
                     $obj->getActiveSheet()->setCellValue($cellName[$si] . ($i + 2), $sv, \PHPExcel_Cell_DataType::TYPE_STRING);
                     if($sk=='img'){
                         if(!empty($sv)){
                             $name = str_replace('http://q.zity.cn/','admin/excel_img/',$sv);
                             if($name){
                                 $a = $this->httpcopy($sv,'/var/www/online/zity/public/'.$name);
                                 // $a = '';
                                 if($a){
                                     // $sv = './admin/img/d1662363206_cangsou.jpg';
                                     $sv = $name;
                                     $objDrawing  = new \PHPExcel_Worksheet_Drawing();
                                     // 获取图片地址
                                     $objDrawing->setPath($sv);
                                     // 设置图片存放在表格的位置
                                     $objDrawing->setCoordinates($cellName[$si] .($i + 2));
                                     // 设置表格宽度
                                     $obj->getActiveSheet()->getColumnDimension($cellName[$si])->setWidth(20);
                                     // 设置表格高度
                                     $obj->getActiveSheet()->getRowDimension(($i + 2))->setRowHeight(60);
                                     // 设置图片宽
                                     //$objDrawing->setWidth(80);
                                     // 设置图片高
                                     $objDrawing->setHeight(60);
                                     // 设置X方向偏移量
                                     $objDrawing->setOffsetX(10);
                                     // 设置Y方向偏移量
                                     $objDrawing->setOffsetY(10);
                                     $objDrawing->setWorksheet($obj->getActiveSheet());
                                 }
                             }
                         }
                     }
                     $si++;
                 }
                 $i++;
             }
             $length = count($title_list);
             $length2 = count($data);
             // 设置加粗和左对齐
             for ($i=0; $i < $length; $i++) {
                 # code...
                 $obj->getActiveSheet()->getStyle($cellName[$i] . '1')->getFont()->setBold(true);
                 // 设置第1-n行，左对齐
                 for ($si = 1; $si <= $length2+1; $si++) {
                     $obj->getActiveSheet()->getStyle($cellName[$i] . $si)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
                 }
             }

             // 导出
             // ob_clean();
             if ($fileType == 'xls') {
                 header('Content-Type: application/vnd.ms-excel');
                 header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
                 header('Cache-Control: max-age=1');
                 $objWriter = new \PHPExcel_Writer_Excel5($obj);
                 $objWriter->save('php://output');
             } elseif ($fileType == 'xlsx') {
                 header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                 header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
                 header('Cache-Control: max-age=1');
                 $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
                 $objWriter->save('php://output');
             }
             return ['code' => 200, 'msg' => '导出成功！'];
         }catch (\Exception $e){
             return ['code' => 500, 'msg' => '导出异常！原因：'.$e->getMessage().'； 位置：'.$e->getLine()];
         }
    }


    

      //excel导出 
      public function place_excel_expord_new($params){

        $send_id = $params['send_id']??1;
        $company_id = $params['company_id']??1;
        $order_no = $params['order_no'];
        $out_url = 'http://116.62.169.253:9080/pc/datawhole/place_excel_expord_new?send_id='.$send_id.'&company_id='.$company_id.'&order_no='.$order_no;
        $order_no = explode(',',$order_no);

        $goods_transfers_detail = db::table('goods_transfers_detail')->whereIn('order_no',$order_no)->get();
        $goods_transfers = db::table('goods_transfers')->whereIn('order_no',$order_no)->get()->toarray();
        $platform_id = $goods_transfers[0]->platform_id;
        $platform_name = db::table('platform')->where('Id',$platform_id)->first()->name;
      
        db::table('goods_transfers')->whereIn('order_no',$order_no)->update(['is_out'=>1,'out_url'=>$out_url]);

        $product = [];
        $total_price = 0;

        foreach ($goods_transfers_detail as $gdv) {
            # code...
            $spu_info = db::table('self_spu_info as a')->leftjoin('product_cate_info as b','a.fabric_one','=','b.id')->where('b.type',1)->where('a.spu_id',$gdv->spu_id)->first();
            $declaration_elements = '';
            if($spu_info){
                $declaration_elements = $spu_info->value;
            }

            $cus = db::table('self_custom_sku')->where('id',$gdv->custom_sku_id)->first();

            $gdv_key = $gdv->order_no.'-'.$gdv->custom_sku_id;
            $product[$gdv_key]['declaration_elements'] = $declaration_elements;
            $product[$gdv_key]['custom_sku'] = $gdv->custom_sku;
            $product[$gdv_key]['custom_sku_id'] = $gdv->custom_sku_id;
            $product[$gdv_key]['name'] = $cus->name;
            $product[$gdv_key]['img'][] = $this->GetCustomskuImg($gdv->custom_sku);
            $product[$gdv_key]['brand'] = '';
            if(isset($product[$gdv_key]['box_num'])){
                $product[$gdv_key]['box_num'] +=  $gdv->receive_num;
            }else{
                $product[$gdv_key]['box_num'] =  $gdv->receive_num;
            }
           
            if(isset($product[$gdv_key]['box_value'])){
                $product[$gdv_key]['box_value'] +=  $gdv->receive_num;
            }else{
                $product[$gdv_key]['box_value'] =  $gdv->receive_num;
            }

            if(isset($product[$gdv_key]['num'])){
                $product[$gdv_key]['num'] +=  1;
            }else{
                $product[$gdv_key]['num'] =  1;
            }

            $product[$gdv_key]['price'] =  $cus->buy_price;
            $product[$gdv_key]['order_no'] =  $gdv->order_no;
  
            $product[$gdv_key]['box_info']  =  $cus->length.'x'.$cus->width.'x'.$cus->height;
            $product[$gdv_key]['weight']  = $cus->weight;
            $goods_transfers_one = db::table('goods_transfers')->where('order_no',$gdv->order_no)->first();
            $attr = json_decode($goods_transfers_one->attr,true);
            $product[$gdv_key]['desc']  = '';
            if(isset($attr['desc'])){
                $product[$gdv_key]['desc']  = $attr['desc'];
            }
         
            $product[$gdv_key]['ds_num']  = $goods_transfers_one->ds_num;
            $product[$gdv_key]['total_num']  = $goods_transfers_one->receive_total_num;

            $platform = db::table('platform')->where('Id',$goods_transfers_one->platform_id)->first()->name;
            $product[$gdv_key]['platform']  = $platform;
            $one_price = $cus->buy_price*$gdv->receive_num;
            $total_price +=$one_price ;
        }


        // return ['code' => 200, 'msg' => '导出成功！','data'=>$product];
        // return $product;
        $m_title = '';

        $receive_total_num = 0;
        $img_data = [];
        foreach ($goods_transfers as $v) {
         
            $attr = json_decode($v->attr,true);
            $m_title.=$attr['m_title'];
            $photo = json_decode($attr['photo'],true);
            if(is_array($photo)){
                $img_data = array_merge($img_data,$photo);
            }

            // {"m_title":"12345","long":"1","width":"2","height":"3","weight":"0.5","desc":"","photo":"[]"}
            # code...
            $receive_total_num  +=$v->receive_total_num;
        }
        //发
        $send =  db::table('product_user_info')->where('id',$send_id)->first();
        //收
        $company  =  db::table('product_user_info')->where('id',$company_id)->first();

        $ds = date('Y-m-d H:i:s',time());

        // if(!$goods_transfers){
        //     return ['code'=>500,'msg'=>'无此单号'];
        // }

        // db::table('goods_transfers')->where('order_no',$order_no)->update(['send_id'=>$send_id,'company_id'=>$company_id]);

        try {
            $tltle = '装箱单';

            $obj = new \PHPExcel();

            $fileName = $tltle. date('Y-m-d');
            $fileType = 'xlsx';

            // 以下内容是excel文件的信息描述信息
            $obj->getProperties()->setTitle($tltle); //设置标题

            // 设置当前sheet
            $obj->setActiveSheetIndex(0);

            // 设置当前sheet的名称
            $obj->getActiveSheet()->setTitle($tltle);

            /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
            $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I','J','K','L','M','N'];
            // 设置excel标题

            // 填充第一行数据
            $sheet = $obj->getActiveSheet();
            $objDrawing  = new \PHPExcel_Worksheet_Drawing();


            //行
            $r_i = 1;

            // $sheet->setCellValue($list[0] . '1', '店铺');
            //1行1列

            // 设置表格宽度
            $obj->getActiveSheet()->getColumnDimension($list[0])->setWidth(20);
            // 设置表格高度
            $obj->getActiveSheet()->getRowDimension($r_i)->setRowHeight(100);

            $img = 'http://116.62.169.253:9080/admin/img/1.png';

  
            $img = $this->httpcopys($img);
       
           

            // 获取图片地址
            $objDrawing->setPath($img);
            // 设置图片存放在表格的位置
            $objDrawing->setCoordinates($list[0] .$r_i);
            // 设置图片宽
            $objDrawing->setWidth(100);
            // 设置图片高
            $objDrawing->setHeight(120);
            $objDrawing->setWorksheet($obj->getActiveSheet());


            $objDrawing  = new \PHPExcel_Worksheet_Drawing();
            //1行2列
            $img = 'http://116.62.169.253:9080/admin/img/2.png';

            $img = $this->httpcopys($img);
    
            // 获取图片地址
            $objDrawing->setPath($img);
            // 设置图片存放在表格的位置
            $objDrawing->setCoordinates($list[7] .$r_i);
            // 设置图片宽
            $objDrawing->setWidth(100);
            // 设置图片高
            $objDrawing->setHeight(80);
            $objDrawing->setWorksheet($obj->getActiveSheet());
            // 设置表格宽度
            $obj->getActiveSheet()->getColumnDimension($list[7])->setWidth(20);
            // // 设置表格高度
            // $sheet->getRowDimension(1)->setRowHeight(60);

            $sheet->mergeCells($list[0].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[13].$r_i); // 合并单元格


            //第二行
            $r_i++;

            $sheet->setCellValue($list[0] . $r_i, '公司官网：http://www.s-ecl.com');
            $sheet->setCellValue($list[7] . $r_i, '更新版本2022-11-30');
            $sheet->mergeCells($list[0].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[13].$r_i); // 合并单元格


            //第三行
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '公司名称/COMPANY NAME');
            $sheet->setCellValue($list[3] . $r_i, $company->company_name);
            $sheet->setCellValue($list[7] . $r_i, 'CONSIGNEE（收货人/电话/详细地址）.');
            $sheet->setCellValue($list[10] . $r_i, $company->addr.';'.$company->user_name.$company->phone);
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格

            //第四行
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '（发货人）PERSON IN-CHARGE');
            $sheet->setCellValue($list[3] . $r_i, $send->user_name);
            $sheet->setCellValue($list[7] . $r_i, 'Country（目的国家）.');
            $sheet->setCellValue($list[10] . $r_i,  $platform_name);
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格


            //第五行
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '发货地址）SUPPLIER ADDRESS');
            $sheet->setCellValue($list[3] . $r_i,  $send->addr);
            $sheet->setCellValue($list[7] . $r_i, '唛头 / MARKING CODE :');
            $sheet->setCellValue($list[10] . $r_i, $m_title);
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格

            //第六行
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '出货日期 / DATE');
            $sheet->setCellValue($list[3] . $r_i, $ds);
            $sheet->setCellValue($list[7] . $r_i, '');
            $sheet->setCellValue($list[10] . $r_i, '');
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格

            //第七行
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '中/英文品名 DESCRIPTION');
            $sheet->setCellValue($list[1] . $r_i, '产品照片 PRODUCT PHOTO');
            $sheet->setCellValue($list[2] . $r_i, '牌子名称 BRAND NAME');
            $sheet->setCellValue($list[3] . $r_i, '材质material');
            $sheet->setCellValue($list[4] . $r_i, '有无电磁/磁性/电池/粉状/液体/膏体');
            $sheet->setCellValue($list[5] . $r_i, '每一箱数量 UNITS PER CARTON');
            $sheet->setCellValue($list[6] . $r_i, '每一箱货值 VALUE PER CARTON');
            $sheet->setCellValue($list[7] . $r_i, '单价 UNIT PRICE');
            $sheet->setCellValue($list[8] . $r_i, '箱号 CARTON NUMBER');
            $sheet->setCellValue($list[9] . $r_i, '件数 PACKAGE');
            $sheet->setCellValue($list[10] . $r_i, '单件规格 PER DIMENSION');
            $sheet->setCellValue($list[11] . $r_i, '单件重量 PER WEIGHT');
            $sheet->setCellValue($list[12] . $r_i, '其他（快递进仓，请备注品名对应的快递单号）');
            $sheet->setCellValue($list[13] . $r_i, '备注（体积）');

            $tj_total = 0;

            foreach ($product as $pv) {
                # code...
                $r_i++;
                $sheet->setCellValue($list[0] . $r_i, $pv['name']);


                $img_count = count($pv['img']);
                // 设置表格宽度
                $obj->getActiveSheet()->getColumnDimension($list[1])->setWidth($img_count*7);
                for ($j=0; $j < $img_count; $j++) { 
                    # code...
                    $objDrawing  = new \PHPExcel_Worksheet_Drawing();
                    //1行2列
                    $img = $pv['img'][$j];
        
                    try {
                        //code...
                        $img = $this->httpcopys($img);
                        // 获取图片地址
                        $objDrawing->setPath($img);
                        // 设置图片存放在表格的位置
                        $objDrawing->setCoordinates($list[1] .$r_i);
                        // 设置图片宽
                        $objDrawing->setWidth(50);
                        // 设置图片高
                        $objDrawing->setHeight(50);
                        $objDrawing->setWorksheet($obj->getActiveSheet());

                        // 设置表格高度
                        $obj->getActiveSheet()->getRowDimension($r_i)->setRowHeight(100);
                        // 设置X方向偏移量
                        $x = $j*50;
                        $objDrawing->setOffsetX($x);
                        // // 设置Y方向偏移量
                        // $objDrawing->setOffsetY(10);
                    } catch (\Throwable $th) {
                        //throw $th;
                        $img = '';
                    }
                    
        
                    
                }

                $sheet->setCellValue($list[2] . $r_i, $pv['brand']);
                $sheet->setCellValue($list[3] . $r_i, $pv['declaration_elements']);
                $sheet->setCellValue($list[4] . $r_i, '无');
                $sheet->setCellValue($list[5] . $r_i,  $pv['box_num']);
                $sheet->setCellValue($list[6] . $r_i,  $pv['box_value']);
                $sheet->setCellValue($list[7] . $r_i,  $pv['price']);
                $sheet->setCellValue($list[8] . $r_i,  $pv['order_no']);
                $sheet->setCellValue($list[9] . $r_i, 1);
                $sheet->setCellValue($list[10] . $r_i, $pv['box_info']);
                $box_info = explode('x',$pv['box_info']);
                $tj = 0;
            
                foreach ($box_info  as $biv) {
                    # code...
                    if((int)$biv>0){
                        if($tj==0){
                            $tj  = $biv;
                        }else{
                            $tj = $tj* $biv;
                        }
      
                    }
           
                }


                $tj = round($tj/1000000,6);
                $tj_total+=$tj;
                
                $sheet->setCellValue($list[11] . $r_i, $pv['weight']);
                $sheet->setCellValue($list[12] . $r_i, $pv['desc']);
                $sheet->setCellValue($list[13] . $r_i,  $tj);
            }
   





            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '总数量 TOTAL PIECES');
            $sheet->setCellValue($list[3] . $r_i, $receive_total_num );
            $sheet->setCellValue($list[7] . $r_i, '总金额 GRAND VALUE（含币种）');
            $sheet->setCellValue($list[10] . $r_i, $total_price);
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格



        
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '总包装件数 TOTAL PACKAGES');
            $sheet->setCellValue($list[3] . $r_i, count($product));
            $sheet->setCellValue($list[7] . $r_i, '立方数 TOTAL m3');
            $sheet->setCellValue($list[10] . $r_i, $tj_total);
            $sheet->mergeCells($list[0].$r_i.':'.$list[2].$r_i); // 合并单元格
            $sheet->mergeCells($list[3].$r_i.':'.$list[6].$r_i); // 合并单元格
            $sheet->mergeCells($list[7].$r_i.':'.$list[9].$r_i); // 合并单元格
            $sheet->mergeCells($list[10].$r_i.':'.$list[13].$r_i); // 合并单元格

        
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '填写要求：红色字体部分为必填项');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格

                    
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '备注：以上品名必须与实际出口品名一致，如有瞒报漏报品名不符，一经查验发现，产生额外费用我司将向客户收取！');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格


                    
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, 'ABOVE COMMODITIES ARE LICENSED FOR THE ULTIMATE DESTINATION SHOWN DIVERSION COUNTRY TO UNITED STATES LAW IS PROHIBITED');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格


                    
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '以上货物为目的国所许可进口,不违反目的国法律');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格


            
                    
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, 'I DECLARE ALL THE INFORMATION CONTAINED IN THIS INVOICE TO BE TRUE AND CORRECT');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格


            
                    
            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '我声明发票上内容真实无误');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格


            $r_i++;
            // $img_data=['http://116.62.169.253:9080/admin/img/4.png','http://116.62.169.253:9080/admin/img/4.png','http://116.62.169.253:9080/admin/img/3.png','http://116.62.169.253:9080/admin/img/2.png'];
                    

            $arrt_count = count($img_data);

            for ($ati=0; $ati < $arrt_count; $ati++) { 
                # code...
                $objDrawing  = new \PHPExcel_Worksheet_Drawing();

                $img = $this->httpcopys($img_data[$ati]);
                // 获取图片地址
                $objDrawing->setPath($img);
                // 设置图片存放在表格的位置
                $objDrawing->setCoordinates($list[0] .$r_i);
                // 设置图片宽
                $objDrawing->setWidth(50);
                // 设置图片高
                $objDrawing->setHeight(50);
                $objDrawing->setWorksheet($obj->getActiveSheet());

                // 设置表格高度
                $obj->getActiveSheet()->getRowDimension($r_i)->setRowHeight(100);
                // 设置X方向偏移量
                if($ati==0){$ax=0;}
                if($ati==1){$ax=150;}
                if($ati==2){$ax=300;}
                if($ati==3){$ax=450;}

                $y=$ati*10;
                $objDrawing->setOffsetY($y);
                $objDrawing->setOffsetX($ax);
            }

            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格



            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '');
            $sheet->mergeCells($list[0].$r_i.':'.$list[13].$r_i); // 合并单元格



            $r_i++;
            $sheet->setCellValue($list[0] . $r_i, '*商品编码');
            $sheet->setCellValue($list[1] . $r_i, '货号');
            $sheet->setCellValue($list[2] . $r_i, '国家');
            $sheet->setCellValue($list[3] . $r_i, '发货时间');
            $sheet->setCellValue($list[4] . $r_i, '箱号');
            $sheet->setCellValue($list[5] . $r_i, '批次号');
            $sheet->setCellValue($list[6] . $r_i, '发货数量');


            // for ($bi=0; $bi < 5; $bi++) { 
            //     # code...
            //     $r_i++;
            //     $sheet->setCellValue($list[0] . $r_i, '612-black-M/L');
            //     $sheet->setCellValue($list[1] . $r_i, '612');
            //     $sheet->setCellValue($list[2] . $r_i, '印尼');
            //     $sheet->setCellValue($list[3] . $r_i, '3月12日');
            //     $sheet->setCellValue($list[4] . $r_i, '5-1');
            //     $sheet->setCellValue($list[5] . $r_i, '612-8');
            //     $sheet->setCellValue($list[6] . $r_i, '800');
            // }

            foreach ($product as $pdv) {
                # code...
                $r_i++;
                $sheet->setCellValue($list[0] . $r_i, $pdv['custom_sku']);
                $sheet->setCellValue($list[1] . $r_i, $pdv['custom_sku_id']);
                $sheet->setCellValue($list[2] . $r_i, $pdv['platform']);
                $sheet->setCellValue($list[3] . $r_i, $ds);
                $sheet->setCellValue($list[4] . $r_i, $pdv['order_no']);
                $sheet->setCellValue($list[5] . $r_i, $pdv['ds_num']);
                $sheet->setCellValue($list[6] . $r_i, $pdv['total_num']);
            }



            // 导出
            // ob_clean();
            if ($fileType == 'xls') {
                header('Content-Type: application/vnd.ms-excel');
                header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
                header('Cache-Control: max-age=1');
                $objWriter = new \PHPExcel_Writer_Excel5($obj);
                $objWriter->save('php://output');
            } elseif ($fileType == 'xlsx') {
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
                header('Cache-Control: max-age=1');
                $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
                $objWriter->save('php://output');
            }
            return ['code' => 200, 'msg' => '导出成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '导出异常！原因：'.$e->getMessage().'； 位置：'.$e->getLine()];
        }
   }

   function httpcopys($url) {
    if($url==''){
        return false;
    }
    $img = str_replace('http://116.62.169.253:9080/','/var/www/test/xin/public/',$url);

    $table = db::table('sys')->first()->table;

    if( $table=='online'){

        $file = '/var/www/online/xin/public/admin/excel_img/'.$img;
    }else{

        $file = '/var/www/test/xin/public/admin/excel_img/'.$img;
    }

    $timeout=60;
    // $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        try {
            
            file_put_contents($file, $temp) ;
        } catch (\Throwable $th) {
            var_dump($file).'----';
            var_dump($th);
        }

        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
        //     $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;

        //     rename($file,$tofile);

           
        //    $url = "/admin/excel_img/".$newname;
        return $img;
        //    return $file;
        } else {
            return false;
        }
    } else {
        echo 2;
        $opts = array(
            "http"=>array(
                "method"=>"GET",
                "header"=>"",
                "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            // //$http_response_header
            // $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;
            // rename($file,$tofile);
            // $url = "/admin/excel_img/".$newname;
            return $img;
        } else {
            return false;
        }
    }
}
    
function httpcopy($url, $file="/test.jpg",$timeout=60) {
    $file = empty($file) ? pathinfo($url,PATHINFO_BASENAME) : $file;
    $dir = pathinfo($file,PATHINFO_DIRNAME);
    !is_dir($dir) && @mkdir($dir,0755,true);
    $url = str_replace(" ","%20",$url);

    if(function_exists('curl_init')) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $temp = curl_exec($ch);
        try {
            file_put_contents($file, $temp) ;
        } catch (\Throwable $th) {
            var_dump($th);
        }

        if(@file_put_contents($file, $temp) && !curl_error($ch)) {
        //     $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;

        //     rename($file,$tofile);

           
        //    $url = "/admin/excel_img/".$newname;
           return $file;
        } else {
            return false;
        }
    } else {
        echo 2;
        $opts = array(
            "http"=>array(
                "method"=>"GET",
                "header"=>"",
                "timeout"=>$timeout)
        );
        $context = stream_context_create($opts);
        if(@copy($url, $file, $context)) {
            // //$http_response_header
            // $tofile = "/www/data/online/new_zity_php/public/admin/excel_img/".$newname;
            // rename($file,$tofile);
            // $url = "/admin/excel_img/".$newname;
            return $file;
        } else {
            return false;
        }
    }
}



    //生产下单导入-其他类型
    public function PlaceOrderOtherImport($params)
    {

        ////获取Excel文件数据
        // $is_new = $params['is_new'] ?? 1;
        $file = $params['file'];
        $user_id = $params['user_id'];
        // $supply_time = $params['supply_time'];
        // $supply_time = strtotime($supply_time);
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();
        $time = time();

        for ($j = 2; $j <= $allRow; $j++) {
            //款号
            $is_new = 2;
            $is_new =  trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if($is_new == '是'){
                $is_new = 1;
            }

            $spu = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
            if (!empty($spu)) {
                $res = Db::table('self_spu')->orwhere('spu', $spu)->orwhere('old_spu', $spu)->first();
                if (!$res) {
                    return ['type' => 'fail', 'msg' => '该spu不存在，请先生成' . $spu];
                }

                $add_list[$j - 2]['spu'] = $spu;

                $product_user_id = '';
                $operate_user_id = '';
                $supply_user_id = '';
        
                //产品负责人
                $product_user = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                if (!empty($product_user)) {
                    $product_user_res = Db::table('users')->where('account', $product_user)->first();
                    if ($product_user_res) {
                        $product_user_id = $product_user_res->Id;
                    }
                    
                }
        
                //运营负责人
                $operate_user = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                if (!empty($operate_user)) {
                    $operate_user_res = Db::table('users')->where('account', $operate_user)->first();
                    if ($operate_user_res) {
                        $operate_user_id = $operate_user_res->Id;
                    }
                   
                }
        
                //供应链负责人
                $supply_user = trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
                if (!empty($supply_user)) {
                    $supply_user_res = Db::table('users')->where('account', $supply_user)->first();
                    if ($supply_user_res) {
                        $supply_user_id = $supply_user_res->Id;
                    }
                    
                }
        
                //下单时间
                $supply_time = trim($Sheet->getCellByColumnAndRow(6, $j)->getValue());
                $supply_time = strtotime($supply_time);

                //英文名
                $add_list[$j - 2]['name_en'] = trim($Sheet->getCellByColumnAndRow(7, $j)->getValue());
                //颜色名
                $add_list[$j - 2]['color_name'] = trim($Sheet->getCellByColumnAndRow(8, $j)->getValue());
                //颜色英文名
                $add_list[$j - 2]['color_name_en'] = trim($Sheet->getCellByColumnAndRow(9, $j)->getValue());
                //颜色英文名
                $add_list[$j - 2]['order'] = trim($Sheet->getCellByColumnAndRow(7, $j)->getValue());
                //品牌
                $add_list[$j - 2]['brand'] = trim($Sheet->getCellByColumnAndRow(8, $j)->getValue());
                //款式
                $add_list[$j - 2]['style'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());

            }
        }


        foreach ($add_list as $value) {

            $query['spu'] = $value['spu'];

            //修改运营负责人和供应链负责人
            $spu_insert['operate_user_id'] = $operate_user_id;
            $spu_insert['supply_user_id'] = $supply_user_id;
            Db::table('amazon_place_order')->where($query)->update($spu_insert);


            $query['color_name_en'] = $value['color_name_en'];
            $query['order'] = $value['order'];
            $query['supply_time'] = $supply_time;
            $is_repeat = Db::table('amazon_place_order')->where($query)->first();
            if (!$is_repeat) {
                $value['supply_time'] = $supply_time;
                $value['product_user_id'] = $product_user_id;
                $value['operate_user_id'] = $operate_user_id;
                $value['supply_user_id'] = $supply_user_id;
                $value['create_time'] = $time;
                $value['is_new'] = $is_new;
                $value['create_user'] = $user_id;

                //判断是否存在颜色名
                $colorres = Db::table('self_color_size')->where('english_name', $value['color_name_en'])->first();
                if ($colorres) {
                    $color_id = $colorres->id;
                } else {
                    //如果没有颜色标识，则手动生成,并存入表
                    if (empty($value['color_identifying'])) {
                        $value['color_identifying'] = $this->GetIdentifying($value['color_name_en']);
                    }
                    $colorinsert['status'] = 1;
                    $colorinsert['name'] = $value['color_name'];
                    $colorinsert['english_name'] = $value['color_name_en'];
                    $colorinsert['identifying'] = $value['color_identifying'];
                    $colorinsert['type'] = 1;
                    $colorinsert['create_time'] = $time;
                    $colorinsert['user_id'] = $user_id;
                    $color_id = Db::table('self_color_size')->insertGetId($colorinsert);
                }

                $spucolorinsert['spu'] = $value['spu'];
                $spucolorinsert['color_id'] = $color_id;
                $spucolorinsert['status'] = 1;
                Db::table('self_spu_color')->insert($spucolorinsert);
                $placeres = Db::table('amazon_place_order')->insert($value);

                if (!$placeres) {
                    return ['type' => 'fail', 'msg' => '导入失败'];
                }
            }
        }

        return ['type' => 'success', 'msg' => '导入成功'];
    }


    //日报列表
    public function DayReportList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $arr = array();

        $arr['user_id'] = $params['user_id'];
        $arr['identity'] = array('day_report_list');
        $powers = $this->powers($arr);
        $list = Db::table('amazon_day_report as a')->leftjoin('amazon_day_report_detail as b','a.id','=','b.report_id')->where('b.status',1);
        $list = $list->select('a.id','a.status','a.user_id','a.link_num','a.ds','a.oa','a.difficulty','a.holiday',DB::raw('sum(b.sales_num) as sales_num'),DB::raw('sum(b.sales_price) as sales_price'),DB::raw('sum(b.ad_price) as ad_price'),DB::raw('sum(b.ad_sales) as ad_sales'));
        // if(!$powers['day_report_list']){
        //     $list = $list->where('a.user_id',$params['user_id']);
        // }

        if(isset($params['find_user_id'])){
            $list->where('a.user_id',$params['find_user_id']);
        }

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];
            $list = $list->whereBetween('a.ds', [$start_time, $end_time]);
        }

        if(isset($params['fasin'])){
            // $details = Db::table('amazon_day_report_detail')->where('b.fasin',$params['fasin'])->groupBy('report_id')->get()->toArray();
            // $ids  = array_column($details,'report_id');
            // $list->whereIn('id',$ids);
            $list = $list->where('b.fasin',$params['fasin']);
        }

        if(isset($params['one_cate_id'])){
            $list = $list->whereIn('b.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $list = $list->whereIn('b.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $list = $list->whereIn('b.three_cate_id',$params['three_cate_id']);
        }

        $list = $list->groupby('a.id');


        $totalNum = $list->get()->count();
        $list = $list->offset($page)->limit($limit)->orderby('a.id', 'desc')->get();

        foreach ($list as $v) {
            # code...
            $res = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$v->ds)->where('end_time','>=',$v->ds)->where('user_id',$v->user_id)->first();

            $v->active_assay = '';
            $v->discount ='';
            $v->problem = '';
            $v->next_plan = '';
            $v->task = '';

            if($res){
                $v->active_assay = $res->active_assay;
                $v->discount = $res->discount;
                $v->problem = $res->problem;
                $v->next_plan = $res->next_plan;
                $v->task = $res->task;
            }


            $v->account = '';
            $v->account = $this->GetUsers($v->user_id)['account'];
            $v->acos = 0;
            $v->tacos = 0;
            if($v->ad_price>0&&$v->ad_sales>0){
                $v->acos = round(($v->ad_price/$v->ad_sales)*100,2);
            }
            if($v->ad_price>0&&$v->sales_price>0){
                $v->tacos = round(($v->ad_price/$v->sales_price)*100,2);
            }
        }

        return [
            'type' => 'success',
            'data' =>  $list,
            'totalNum' => $totalNum,
        ];

    }

    //日报fasin
    public function DayReportByFasin($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }


        $list = Db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.status',1);
        $list = $list->select('a.*','b.holiday','b.user_id','b.ds','b.oa','b.difficulty');
        // if(!$powers['day_report_list']){
        //     $list = $list->where('a.user_id',$params['user_id']);
        // }

        if(isset($params['find_user_id'])){
            $list->where('b.user_id',$params['find_user_id']);
        }


        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];
            $list = $list->whereBetween('b.ds', [$start_time, $end_time]);

        }else{
            $start_time = date('Y-m-d 00:00:00',time());
            $end_time = date('Y-m-d 23:59:59',time());
        }

        if(isset($params['fasin'])){
            // $details = Db::table('amazon_day_report_detail')->where('b.fasin',$params['fasin'])->groupBy('report_id')->get()->toArray();
            // $ids  = array_column($details,'report_id');
            // $list->whereIn('id',$ids);
            $list = $list->where('a.fasin',$params['fasin']);
        }

        if(isset($params['holiday'])){
            $list = $list->where('b.holiday',$params['holiday']);
        }
                
        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }

        if(isset($params['one_cate_id'])){
            $list = $list->whereIn('a.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $list = $list->whereIn('a.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $list = $list->whereIn('a.three_cate_id',$params['three_cate_id']);
        }

        if(isset($params['warn_word'])){
            // $list = $list->orderby('b.id', 'desc')->get();
            $warn = db::table('amazon_day_report_warn')->where('id',1)->first();
            // $warn_list = [];
            foreach ($params['warn_word'] as $warn_word) {
                # code...
                $list = $list->where('a.'.$warn_word,'>',$warn->$warn_word);
            }

        }


        $totalNum = $list->get()->count();
        $list = $list->offset($page)->limit($limit)->orderby('b.ds', 'desc')->get();
        
        // $list = $list->groupby('a.id');

        //上周时间
        $lastweek_start = date("Y-m-d H:i:s",(strtotime($start_time)-(86400*7)));
        $lastweek_end = date("Y-m-d H:i:s",(strtotime($end_time)-(86400*7)));
        //获取上周月份
        $lastweek_moon = (int)date("m",strtotime($lastweek_start));
        //下周月份
        $nextweek_moon = (int)date("m",(strtotime($start_time)+(86400*7)));
        //本周月份
        $week_moon = (int)date("m",(strtotime($start_time)));


        foreach ($list as $v) {
            # code...
            $res = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$v->ds)->where('end_time','>=',$v->ds)->where('user_id',$v->user_id)->first();

            $v->cate_name = $this->GetCategory($v->one_cate_id)['name'].$this->GetCategory($v->three_cate_id)['name'];
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];
            $v->active_assay = '';
            $v->discount ='';
            $v->problem = '';
            $v->next_plan = '';
            $v->task = '';

            if($res){
                $v->active_assay = $res->active_assay;
                $v->discount = $res->discount;
                $v->problem = $res->problem;
                $v->next_plan = $res->next_plan;
                $v->task = $res->task;
            }



            $v->u_time = date('Y-m-d',strtotime($v->ds)-86400);

            $v->account = '';
            $v->account = $this->GetUsers($v->user_id)['account'];
            // $v->acos = 0;
            // $v->tacos = 0;
            // if($v->ad_price>0&&$v->ad_sales>0){
            //     $v->acos = round(($v->ad_price/$v->ad_sales)*100,2);
            // }
            // if($v->ad_price>0&&$v->sales_price>0){
            //     $v->tacos = round(($v->ad_price/$v->sales_price)*100,2);
            // }

            $v->acos = (int)$v->acos;
            $v->tacos = (int)$v->tacos;
            $v->fba_inventory = (int)$v->fba_inventory;
            $v->pc_flow_rate = (int)$v->pc_flow_rate;
            $v->all_flow_rate = (int)$v->all_flow_rate;

            
            // if(isset($params['warn_word'])){
            //     //超过警戒线的加入数组
            //     foreach ($params['warn_word'] as $warn_word) {
            //         # code...
            //         if($v->$warn_word>$warn->$warn_word){
            //             $warn_list[] = $v;
            //             // $v->test = $warn_word.'-'.$v->$warn_word.'-'.$warn->$warn_word;

            //         }

            //     }
            // }


              
            //销量（月）
            $lastweek_month_sales = 0;
            $nextweek_month_sales = 0;
            $week_month_sales = 0;


            //销售额（月）
            $lastweek_month_sales_total = 0;
            $nextweek_month_sales_total = 0;
            $week_month_sales_total = 0;


            //销售目标（周）
            $lastweek_sales_plan = 0;
            $nextweek_sales_plan = 0;
            $week_sales_plan = 0;
            //销量（周）
            $lastweek_sales = 0;
            $nextweek_sales = 0;
            $week_sales = 0;

            //销售额目标（周）
            $lastweek_sales_total_plan = 0;
            $nextweek_sales_total_plan = 0;
            $week_sales_total_plan = 0;

            //销售额（周）
            $lastweek_sales_total = 0;
            $nextweek_sales_total = 0;
            $week_sales_total = 0;

            //广告花费(月)
            $lastweek_month_ad = 0;
            $nextweek_month_ad = 0;
            $week_month_ad = 0;

            //广告花费(周)
            $lastweek_ad = 0;
            $nextweek_ad = 0;
            $week_ad = 0;

            $fasin_codes = db::table('amazon_fasin_bind')->where('fasin',$v->fasin)->where('shop_id',$v->shop_id)->first();
            

            //获取计划数据
            if($fasin_codes){
                $plv =  db::table('amazon_fasin_plan_info')->where('fasin_code',$fasin_codes->fasin_code)->first();
                //上月$lastweek_moon  下月$nextweek_moon

                if($plv){
                    //销量字段
                    $lastweekmonth_sales_word = 'month_sales'.$lastweek_moon;
                    $nextweekmonth_sales_word = 'month_sales'.$nextweek_moon;
                    $weekmonth_sales_word = 'month_sales'.$week_moon;


                    //均价字段
                    $lastweekmonth_price_word = 'month_price'.$lastweek_moon;
                    $nextweekmonth_price_word = 'month_price'.$nextweek_moon;
                    $weekmonth_price_word = 'month_price'.$week_moon;

                    //广告花费字段ad_spend3
                    $lastweekmonth_adspend_word = 'ad_spend'.$lastweek_moon;
                    $nextweekmonth_adspend_word = 'ad_spend'.$nextweek_moon;
                    $weekmonth_adspend_word = 'ad_spend'.$week_moon;


                    # code...
                    //上月销量
                    $lastweek_month_sales = $plv->$lastweekmonth_sales_word;
                    //上月销售额 = 上月销量*上月均价
                    $lastweek_month_sales_total = $plv->$lastweekmonth_sales_word * $plv->$lastweekmonth_price_word;
                    //上月广告花费
                    $lastweek_month_ad = $plv->$lastweekmonth_adspend_word;



                    //下月销量
                    $nextweek_month_sales =$plv->$nextweekmonth_sales_word;
                    //下月销售额 = 下月销量*下月均价
                    $nextweek_month_sales_total = $plv->$nextweekmonth_sales_word * $plv->$nextweekmonth_price_word;
                    //下月广告花费
                    $nextweek_month_ad = $plv->$nextweekmonth_adspend_word;



                    //本月销量
                    $week_month_sales =$plv->$weekmonth_sales_word;
                    //本月销售额 = 本月销量*本月均价
                    $week_month_sales_total = $plv->$weekmonth_sales_word * $plv->$weekmonth_price_word;
                    //本月广告花费
                    $week_month_ad = $plv->$weekmonth_adspend_word;

                }
             

            }


            //获取上周销售额 和销量

            $lastweek_res = db::table('amazon_day_report as a')->leftjoin('amazon_day_report_detail as b','a.id','=','b.report_id')->where('b.status',1)->whereBetween('a.ds', [$lastweek_start, $lastweek_end])->where('b.fasin',$v->fasin)->select(DB::raw('GROUP_CONCAT(a.id) as ids'),DB::raw('sum(b.sales_num)as sales_num'),DB::raw('sum(b.sales_price)as sales_price'),DB::raw('sum(b.ad_price)as ad_price'),DB::raw('sum(b.ad_sales)as ad_sales'),DB::raw('sum(b.ad_click_rate)as ad_click_rate'),DB::raw('sum(b.ad_out_order)as ad_out_order'),DB::raw('sum(b.week_total_flow)as week_total_flow'),DB::raw('sum(b.week_pc_flow)as week_pc_flow'),DB::raw('sum(b.week_wap_flow)as week_wap_flow'))->get();
            $lastweek_res =  $lastweek_res[0];
            $v->lastweek_res = $lastweek_res;


            // //本周广告平均率
            // $v->ad_click_rate = 0;
            // if($v->link_num>0&&$v->ad_click_rate>0){
            //     $v->ad_click_rate = round($v->ad_click_rate/$v->link_num,2);
            // }

            // $last_ids =  explode(",",$lastweek_res->ids);
            // $last_link_num = 0;
            // if($last_ids){
            //     $last_link_num = count($last_ids);
            // }

  
            //  //上周广告平均率
            // $v->last_ad_click_rate = 0;
            // if($last_link_num>0&&$lastweek_res->ad_click_rate>0){
            //     $v->last_ad_click_rate = round($lastweek_res->ad_click_rate/$last_link_num,2);
            // }

            // //点击率与上周相比
            // $v->ad_click_rate_contrast = $v->ad_click_rate - $v->last_ad_click_rate;

            //广告出单占比  广告出单/销量/
            $v->ad_out_order_rate = 0;
            if($v->ad_out_order>0&&$v->sales_num>0){
                $v->ad_out_order_rate = round($v->ad_out_order/$v->sales_num*100,2);
            }


            // //上周广告出单占比  广告出单/销量/
            // $v->last_ad_out_order_rate = 0;
            // if($lastweek_res->ad_out_order>0&&$lastweek_res->sales_num>0){
            //     $v->last_ad_out_order_rate = round($lastweek_res->ad_out_order/$lastweek_res->sales_num*100,2);
            // }

            // //广告出单占比与上周相比
            // $v->ad_out_order_rate_contrast =  $v->ad_out_order_rate -  $v->last_ad_out_order_rate;

            // //上周总流量
            // $v->last_week_total_flow = $lastweek_res->week_total_flow;

            // //总涨幅率  = 本周-上周 /上周
            // $v->total_flow_rata = 0;
            // if(($v->week_total_flow-$v->last_week_total_flow)>0&&$v->last_week_total_flow>0){
            //     $v->total_flow_rata = round(($v->week_total_flow-$v->last_week_total_flow)/$v->last_week_total_flow*100,2);
            // }

            // //pc流量占比 = pc流量/总流量
            // $v->week_pc_flow_rate = 0;
            // if($v->week_pc_flow>0&&$v->week_total_flow>0){
            //     $v->week_pc_flow_rate = round($v->week_pc_flow/$v->week_total_flow*100,2);
            // }


            //  //移动流量占比 = 移动流量/总流量
            //  $v->week_wap_flow_rate = 0;
            //  if($v->week_wap_flow>0&&$v->week_total_flow>0){
            //      $v->week_wap_flow_rate = round($v->week_wap_flow/$v->week_total_flow*100,2);
            //  }
 
            //  //PC转化率=销量/PC流量
            //  $v->pc_flow_rate = 0;
            //  if($v->week_pc_flow>0&&$v->sales_num>0){
            //     $v->pc_flow_rate = round($v->sales_num/$v->week_pc_flow*100,2);
            // }

            // //总转化率 = 销量/总流量
            // $v->all_flow_rate = 0;
            // if($v->week_total_flow>0&&$v->sales_num>0){
            //    $v->all_flow_rate = round($v->sales_num/$v->week_total_flow*100,2);
            // }

            // //上周总转化率
            // $v->last_all_flow_rate = 0;
            // if($lastweek_res->week_total_flow>0&&$lastweek_res->sales_num>0){
            //     $v->last_all_flow_rate = round($lastweek_res->sales_num/$lastweek_res->week_total_flow*100,2);
            // }

            // //总转化率与上周相比
            // $v->all_flow_rate_contrast = $v->all_flow_rate - $v->last_all_flow_rate;

            // //总转化率差异 = 总转化率-4
            // $v->all_flow_rate_dec = $v->all_flow_rate-4;
            
            //销售目标
            //销量
            if($lastweek_month_sales>0){
                $lastweek_sales_plan = ceil($lastweek_month_sales/30);
            }
            if($nextweek_month_sales>0){
                $nextweek_sales_plan = ceil($nextweek_month_sales/30);
            }
            if($week_month_sales>0){
                $week_sales_plan = ceil($week_month_sales/30);
            }


            //销售额
            if($lastweek_month_sales_total>0){
                $lastweek_sales_total_plan = ceil($lastweek_month_sales_total/30);
            }
            if($nextweek_month_sales_total>0){
                $nextweek_sales_total_plan = ceil($nextweek_month_sales_total/30);
            }
            if($week_month_sales_total>0){
                $week_sales_total_plan = ceil($week_month_sales_total/30);
            }





            
            //目标销量
            $v->sales_num_plan = $week_sales_plan;

            //下周销售目标
            $v->sales_num_plan_next =$nextweek_sales_plan;

            //销量完成率   销量/目标销量
            $v->sales_num_rate = 0;
            if($v->sales_num>0&&$v->sales_num_plan>0){
                $v->sales_num_rate = round(($v->sales_num/$v->sales_num_plan)*100,2);
            }


            // $v->sales_num_growth_rate = 0;
            // //销量涨幅率  这期销量-上期销量/上期销量
            // if($lastweek_res->sales_num>$v->sales_num){
            //     if(($lastweek_res->sales_num - $v->sales_num)>0&&$lastweek_res->sales_num>0){
            //         $v->sales_num_growth_rate = round((($lastweek_res->sales_num - $v->sales_num)/$lastweek_res->sales_num)*100,2);
            //         $v->sales_num_growth_rate =  0 - $v->sales_num_growth_rate;
            //     }
           
            // }else{
            //     if(($v->sales_num - $lastweek_res->sales_num)>0&&$lastweek_res->sales_num>0){
            //         $v->sales_num_growth_rate = round((($v->sales_num - $lastweek_res->sales_num)/$lastweek_res->sales_num)*100,2);
            //     }
              
            // }
        

            //目标销售额
            $v->sales_price_plan = $week_sales_total_plan;
            //下周销售目标
            $v->sales_price_plan_next = $nextweek_sales_total_plan;


            //销售额完成率  销售额/目标销售额
            $v->sales_price_rate  = 0;
            if($v->sales_price>0&&$v->sales_price_plan>0){
                $v->sales_price_rate = round(($v->sales_price/$v->sales_price_plan)*100,2);
            }

            //业绩是否完成
            $v->is_perform = 0;

            if($v->sales_price>$v->sales_price_plan){
                $v->is_perform = 1;
            }

            // //销售额涨幅率 这期销售额-上期销量/上期销售额
            // $v->sales_price_growth_rate = 0;
            // if($lastweek_res->sales_price>$v->sales_price){
            //     if(($lastweek_res->sales_price - $v->sales_price)>0&&$lastweek_res->sales_price>0){
            //         $v->sales_price_growth_rate = round((( $lastweek_res->sales_price - $v->sales_price)/$lastweek_res->sales_price)*100,2);
            //         $v->sales_price_growth_rate =  0 - $v->sales_price_growth_rate;
            //     }
           
            // }else{
            //     if(($v->sales_price - $lastweek_res->sales_price)>0&&$lastweek_res->sales_price>0){
            //         $v->sales_price_growth_rate = round((($v->sales_price - $lastweek_res->sales_price)/$lastweek_res->sales_price)*100,2);
            //     }
              
            // }


            //目标广告费
            $v->ad_price_plan = $week_ad;


            //ACOS与上周相比
            $v->acos_contrast = 0;
            //上周aocs
            $lastweek_acos = 0;
            $lastweek_tacos = 0;

            if($lastweek_res->ad_price>0&&$lastweek_res->ad_sales>0){
                $lastweek_acos = round(($lastweek_res->ad_price/$lastweek_res->ad_sales)*100,2);
            }
            if($lastweek_res->ad_price>0&&$lastweek_res->sales_price>0){
                $lastweek_tacos = round(($lastweek_res->ad_price/$lastweek_res->sales_price)*100,2);
            }

            $v->acos_contrast = round($v->acos - $lastweek_acos,2);

            
            //目标tacos
            $v->tacos_plan = 0;
 
            //TACOS是否超目标
            $v->is_tacos = 0;

            //TACOS与上周相比
            $v->tacos_contrast = 0;
            $v->tacos_contrast = round($v->tacos - $lastweek_tacos,2);

            //下周目标TACOS
            $v->tacos_plan_next = 0;

            // //库存数量
            // $v->fba_inventory = 0;
            // //库存于上周相比
            // $v->fba_inventory_contrast = 0;
            // //库存周转天数
            // $v->fba_inventory_day = 0;


            // //PC转化率=销量/PC流量
            // $v->pc_flow_rate = 0;
            // if($v->week_pc_flow>0&&$v->sales_num>0){
            //     $v->pc_flow_rate = round($v->sales_num/$v->week_pc_flow*100,2);
            // }

            // //总转化率 = 销量/总流量
            // $v->all_flow_rate = 0;
            // if($v->week_total_flow>0&&$v->sales_num>0){
            //     $v->all_flow_rate = round($v->sales_num/$v->week_total_flow*100,2);
            // }
        }


        // if(isset($params['warn_word'])){
        //     //超过警戒线的加入数组
        //     $list= [];

        //     foreach ($warn_list as $k => $v) {
        //         # code...
        //         for ($i=$limit * ($pagenum-1); $i < $limit * $pagenum; $i++) { 
        //             # code...
        //             if($k==$i){
        //                 $list[] = $v;
        //             }
        //         }
    
        //     }

        //     $totalNum = count($list);
        // }


        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='日报-fasin'.time();
            $p['title_list']  = [
                'fasin'=>'fasin',
                'cate_name'=>'分类',
                'shop_name'=>'店名',
                'sales_num'=>'销量',
                'acos'=>'acos',
                'tacos'=>'tacos',
                'sales_price'=>'销售额',
                'ad_price'=>'广告费用',
                'ad_sales'=>'广告销售额',
                'cate_rank'=>'大类排名',
                'fba_inventory'=>'fba仓库存',
                'ad_num'=>'广告组数量',
                'ad_click_rate'=>'广告平均点击率',
                'ad_out_order'=>'广告出单',
                'week_total_flow'=>'日总流量',
                'week_pc_flow'=>'日PC流量',
                'week_wap_flow'=>'日移动流量',
                'ds'=>'中国时间',
                'u_time'=>'美国时间',
                'account'=>'运营',
                'pc_flow_rate'=>'PC转化率',
                'all_flow_rate'=>'总转化率',
                'active_assay'=>'本周活动、活动效果分析',
                'discount'=>'本周折扣',
                'problem'=>'本周问题',
                'next_plan'=>'下周计划',
                'task'=>'本周公共任务完成情况',
            ];

            // $this->excel_expord($p);
                
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = '日报-fasin-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type'=>'fail','msg'=>'加入队列失败'];
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }

        return [
            'type' => 'success',
            'data' =>  $list,
            'totalNum' => $totalNum,
        ];


    }


    //设置日报警戒线
    public function SetDayReportWarn($params){
        if(isset($params['fba_inventory'])){
            $i['fba_inventory'] = $params['fba_inventory'];
        }
        if(isset($params['acos'])){
            $i['acos'] = $params['acos'];
        }
        if(isset($params['tacos'])){
            $i['tacos'] = $params['tacos'];
        }
        if(isset($params['pc_flow_rate'])){
            $i['pc_flow_rate'] = $params['pc_flow_rate'];
        }
        if(isset($params['all_flow_rate'])){
            $i['all_flow_rate'] = $params['all_flow_rate'];
        }
    
        db::table('amazon_day_report_warn')->where('id',1)->update($i);
        return ['type'=>'success','msg'=>'修改成功'];
    }

    //查询日报警戒线
    public function DayReportWarn($params){
        $warn = db::table('amazon_day_report_warn')->where('id',1)->first();
        return ['type'=>'success','data'=>$warn];
    }

    //日报-周报-faisn
    public function WeekReportByFasin($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }


        $list = Db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.status',1);
        $list = $list->select(DB::raw('sum(a.sales_num) as sales_num'),DB::raw('sum(a.sales_price) as sales_price'),DB::raw('sum(a.ad_price) as ad_price'),DB::raw('sum(a.ad_sales) as ad_sales'),DB::raw('sum(a.ad_num) as ad_num'),DB::raw('sum(a.ad_click_rate) as ad_click_rate'),DB::raw('sum(a.ad_out_order) as ad_out_order'),DB::raw('sum(a.week_total_flow) as week_total_flow'),DB::raw('sum(a.week_pc_flow) as week_pc_flow'),DB::raw('sum(a.week_wap_flow) as week_wap_flow'),'a.shop_id','a.one_cate_id','a.three_cate_id','a.fasin','b.user_id','b.ds','b.oa','b.difficulty')->groupby('a.fasin');
        // if(!$powers['day_report_list']){
        //     $list = $list->where('a.user_id',$params['user_id']);
        // }

        if(isset($params['find_user_id'])){
            $list->where('b.user_id',$params['find_user_id']);
        }

        $days = 1;

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = $params['start_time'];
            $end_time = $params['end_time'];
            $list = $list->whereBetween('b.ds', [$start_time, $end_time]);
            $days = round((strtotime($end_time)-strtotime($start_time))/86400)+1;
        }else{
            $start_time = date('Y-m-d 00:00:00',time());
            $end_time = date('Y-m-d 23:59:59',time());
            $list = $list->whereBetween('b.ds', [$start_time, $end_time]);
        }

        if(isset($params['fasin'])){
            // $details = Db::table('amazon_day_report_detail')->where('b.fasin',$params['fasin'])->groupBy('report_id')->get()->toArray();
            // $ids  = array_column($details,'report_id');
            // $list->whereIn('id',$ids);
            $list = $list->where('a.fasin',$params['fasin']);
        }

        if(isset($params['one_cate_id'])){
            $list = $list->whereIn('a.one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $list = $list->whereIn('a.two_cate_id',$params['two_cate_id']);
        }
        if(isset($params['three_cate_id'])){
            $list = $list->whereIn('a.three_cate_id',$params['three_cate_id']);
        }

        if(isset($params['holiday'])){
            $list = $list->where('b.holiday',$params['holiday']);
        }
                
        if(isset($params['shop_id'])){
            $list = $list->where('a.shop_id',$params['shop_id']);
        }


        if(isset($params['warn_word'])){
            // $list = $list->orderby('b.id', 'desc')->get();
            $warn = db::table('amazon_day_report_warn')->where('id',1)->first();
            $warn_list = [];
            // foreach ($params['warn_word'] as $warn_word) {
            //     # code...
            //     $list = $list->where('a.'.$warn_word,'>',$warn->$warn_word);
            // }
            $list = $list->orderby('b.ds', 'desc')->get();

        }else{
            $totalNum = $list->get()->count();
            $list = $list->offset($page)->limit($limit)->orderby('b.ds', 'desc')->get();
        }

        // $list = $list->groupby('a.id');



        foreach ($list as $v) {
            # code...
            // $res = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$v->ds)->where('end_time','>=',$v->ds)->where('user_id',$v->user_id)->first();

            // $v->active_assay = '';
            // $v->discount ='';
            // $v->problem = '';
            // $v->next_plan = '';
            // $v->task = '';


            // if($res){
            //     $v->active_assay = $res->active_assay;
            //     $v->discount = $res->discount;
            //     $v->problem = $res->problem;
            //     $v->next_plan = $res->next_plan;
            //     $v->task = $res->task;
            // }

            $v->cate_name = $this->GetCategory($v->one_cate_id)['name'].$this->GetCategory($v->three_cate_id)['name'];
            $v->shop_name = $this->GetShop($v->shop_id)['shop_name'];

            $v->days =  $days;

            if($v->ad_click_rate>0){
                $v->ad_click_rate = round($v->ad_click_rate/$v->days,2);
            }


            // if($v->days>1){
            //     $v->fasin_detail = [];
            //     $fasin_detail =  Db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.status',1)->where('a.fasin',$v->fasin)->whereBetween('b.ds', [$start_time, $end_time])->select('a.*','b.ds')->get();
            //     if($fasin_detail){
            //         $v->fasin_detail = $fasin_detail;
            //     }

            // }
            $u_start = date('Y-m-d',strtotime($start_time)-86400);
            $u_end = date('Y-m-d',strtotime($end_time)-86400);

            $s_start =  date('Y-m-d',strtotime($start_time));
            $s_end =  date('Y-m-d',strtotime($end_time));
            $v->time = $s_start.'-'.$s_end;
            $v->u_time = $u_start.'-'.$u_end;

            $v->only_key = $v->fasin.$v->time;

            $v->account = '';
            $v->account = $this->GetUsers($v->user_id)['account'];
            $v->acos = 0;
            $v->tacos = 0;
            if($v->ad_price>0&&$v->ad_sales>0){
                $v->acos = round(($v->ad_price/$v->ad_sales)*100,2);
            }
            if($v->ad_price>0&&$v->sales_price>0){
                $v->tacos = round(($v->ad_price/$v->sales_price)*100,2);
            }

            //PC转化率=销量/PC流量
            $v->pc_flow_rate = 0;
            if($v->week_pc_flow>0&&$v->sales_num>0){
                $v->pc_flow_rate = round($v->sales_num/$v->week_pc_flow*100,2);
            }

            //总转化率 = 销量/总流量
            $v->all_flow_rate = 0;
            if($v->week_total_flow>0&&$v->sales_num>0){
                $v->all_flow_rate = round($v->sales_num/$v->week_total_flow*100,2);
            }


                        
            if(isset($params['warn_word'])){
                //超过警戒线的加入数组
                foreach ($params['warn_word'] as $warn_word) {
                    # code...
                    if($v->$warn_word>$warn->$warn_word){
                        $warn_list[] = $v;
                        // $v->test = $warn_word.'-'.$v->$warn_word.'-'.$warn->$warn_word;

                    }

                }
            }

        }



        if(isset($params['warn_word'])){
            //超过警戒线的加入数组
            $list= [];

            foreach ($warn_list as $k => $v) {
                # code...
                for ($i=$limit * ($pagenum-1); $i < $limit * $pagenum; $i++) { 
                    # code...
                    if($k==$i){
                        $list[] = $v;
                    }
                }
    
            }


            $totalNum = count($list);
        }



        //上周时间
        $lastweek_start = date("Y-m-d H:i:s",(strtotime($start_time)-(86400*7)));
        $lastweek_end = date("Y-m-d H:i:s",(strtotime($end_time)-(86400*7)));
        //获取上周月份
        $lastweek_moon = (int)date("m",strtotime($lastweek_start));
        //下周月份
        $nextweek_moon = (int)date("m",(strtotime($start_time)+(86400*7)));
        //本周月份
        $week_moon = (int)date("m",(strtotime($start_time)));


        foreach ($list as $v) {
            # code...
            $res = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$v->ds)->where('end_time','>=',$v->ds)->where('user_id',$v->user_id)->first();

            $v->active_assay = '';
            $v->discount ='';
            $v->problem = '';
            $v->next_plan = '';
            $v->task = '';

            if($res){
                $v->active_assay = $res->active_assay;
                $v->discount = $res->discount;
                $v->problem = $res->problem;
                $v->next_plan = $res->next_plan;
                $v->task = $res->task;
            }
            
            if($v->days>1){
                $v->fasin_detail = [];
                $fasin_detail =  Db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.status',1)->where('a.fasin',$v->fasin)->whereBetween('b.ds', [$start_time, $end_time])->select('a.*','b.ds')->get();
                if($fasin_detail){
                    $v->fasin_detail = $fasin_detail;
                }

            }



            
            //销量（月）
            $lastweek_month_sales = 0;
            $nextweek_month_sales = 0;
            $week_month_sales = 0;


            //销售额（月）
            $lastweek_month_sales_total = 0;
            $nextweek_month_sales_total = 0;
            $week_month_sales_total = 0;


            //销售目标（周）
            $lastweek_sales_plan = 0;
            $nextweek_sales_plan = 0;
            $week_sales_plan = 0;
            //销量（周）
            $lastweek_sales = 0;
            $nextweek_sales = 0;
            $week_sales = 0;

            //销售额目标（周）
            $lastweek_sales_total_plan = 0;
            $nextweek_sales_total_plan = 0;
            $week_sales_total_plan = 0;

            //销售额（周）
            $lastweek_sales_total = 0;
            $nextweek_sales_total = 0;
            $week_sales_total = 0;

            //广告花费(月)
            $lastweek_month_ad = 0;
            $nextweek_month_ad = 0;
            $week_month_ad = 0;

            //广告花费(周)
            $lastweek_ad = 0;
            $nextweek_ad = 0;
            $week_ad = 0;

            $fasin_codes = db::table('amazon_fasin_bind')->where('fasin',$v->fasin)->where('shop_id',$v->shop_id)->first();
            

            //获取计划数据
            if($fasin_codes){
                $plv =  db::table('amazon_fasin_plan_info')->where('fasin_code',$fasin_codes->fasin_code)->first();
                //上月$lastweek_moon  下月$nextweek_moon

                if($plv){
                    //销量字段
                    $lastweekmonth_sales_word = 'month_sales'.$lastweek_moon;
                    $nextweekmonth_sales_word = 'month_sales'.$nextweek_moon;
                    $weekmonth_sales_word = 'month_sales'.$week_moon;


                    //均价字段
                    $lastweekmonth_price_word = 'month_price'.$lastweek_moon;
                    $nextweekmonth_price_word = 'month_price'.$nextweek_moon;
                    $weekmonth_price_word = 'month_price'.$week_moon;

                    //广告花费字段ad_spend3
                    $lastweekmonth_adspend_word = 'ad_spend'.$lastweek_moon;
                    $nextweekmonth_adspend_word = 'ad_spend'.$nextweek_moon;
                    $weekmonth_adspend_word = 'ad_spend'.$week_moon;


                    # code...
                    //上月销量
                    $lastweek_month_sales = $plv->$lastweekmonth_sales_word;
                    //上月销售额 = 上月销量*上月均价
                    $lastweek_month_sales_total = $plv->$lastweekmonth_sales_word * $plv->$lastweekmonth_price_word;
                    //上月广告花费
                    $lastweek_month_ad = $plv->$lastweekmonth_adspend_word;



                    //下月销量
                    $nextweek_month_sales =$plv->$nextweekmonth_sales_word;
                    //下月销售额 = 下月销量*下月均价
                    $nextweek_month_sales_total = $plv->$nextweekmonth_sales_word * $plv->$nextweekmonth_price_word;
                    //下月广告花费
                    $nextweek_month_ad = $plv->$nextweekmonth_adspend_word;



                    //本月销量
                    $week_month_sales =$plv->$weekmonth_sales_word;
                    //本月销售额 = 本月销量*本月均价
                    $week_month_sales_total = $plv->$weekmonth_sales_word * $plv->$weekmonth_price_word;
                    //本月广告花费
                    $week_month_ad = $plv->$weekmonth_adspend_word;

                }
             

            }


            //获取上周销售额 和销量

            $lastweek_res = db::table('amazon_day_report as a')->leftjoin('amazon_day_report_detail as b','a.id','=','b.report_id')->where('b.status',1)->whereBetween('a.ds', [$lastweek_start, $lastweek_end])->where('b.fasin',$v->fasin)->select(DB::raw('GROUP_CONCAT(a.id) as ids'),DB::raw('sum(b.sales_num)as sales_num'),DB::raw('sum(b.sales_price)as sales_price'),DB::raw('sum(b.ad_price)as ad_price'),DB::raw('sum(b.ad_sales)as ad_sales'),DB::raw('sum(b.ad_click_rate)as ad_click_rate'),DB::raw('sum(b.ad_out_order)as ad_out_order'),DB::raw('sum(b.week_total_flow)as week_total_flow'),DB::raw('sum(b.week_pc_flow)as week_pc_flow'),DB::raw('sum(b.week_wap_flow)as week_wap_flow'))->get();
            $lastweek_res =  $lastweek_res[0];
            $v->lastweek_res = $lastweek_res;


            // //本周广告平均率
            // $v->ad_click_rate = 0;
            // if($v->link_num>0&&$v->ad_click_rate>0){
            //     $v->ad_click_rate = round($v->ad_click_rate/$v->link_num,2);
            // }

            // $last_ids =  explode(",",$lastweek_res->ids);
            // $last_link_num = 0;
            // if($last_ids){
            //     $last_link_num = count($last_ids);
            // }

  
            //  //上周广告平均率
            // $v->last_ad_click_rate = 0;
            // if($last_link_num>0&&$lastweek_res->ad_click_rate>0){
            //     $v->last_ad_click_rate = round($lastweek_res->ad_click_rate/$last_link_num,2);
            // }

            // //点击率与上周相比
            // $v->ad_click_rate_contrast = $v->ad_click_rate - $v->last_ad_click_rate;

            //广告出单占比  广告出单/销量/
            $v->ad_out_order_rate = 0;
            if($v->ad_out_order>0&&$v->sales_num>0){
                $v->ad_out_order_rate = round($v->ad_out_order/$v->sales_num*100,2);
            }


            // //上周广告出单占比  广告出单/销量/
            // $v->last_ad_out_order_rate = 0;
            // if($lastweek_res->ad_out_order>0&&$lastweek_res->sales_num>0){
            //     $v->last_ad_out_order_rate = round($lastweek_res->ad_out_order/$lastweek_res->sales_num*100,2);
            // }

            // //广告出单占比与上周相比
            // $v->ad_out_order_rate_contrast =  $v->ad_out_order_rate -  $v->last_ad_out_order_rate;

            // //上周总流量
            // $v->last_week_total_flow = $lastweek_res->week_total_flow;

            // //总涨幅率  = 本周-上周 /上周
            // $v->total_flow_rata = 0;
            // if(($v->week_total_flow-$v->last_week_total_flow)>0&&$v->last_week_total_flow>0){
            //     $v->total_flow_rata = round(($v->week_total_flow-$v->last_week_total_flow)/$v->last_week_total_flow*100,2);
            // }

            // //pc流量占比 = pc流量/总流量
            // $v->week_pc_flow_rate = 0;
            // if($v->week_pc_flow>0&&$v->week_total_flow>0){
            //     $v->week_pc_flow_rate = round($v->week_pc_flow/$v->week_total_flow*100,2);
            // }


            //  //移动流量占比 = 移动流量/总流量
            //  $v->week_wap_flow_rate = 0;
            //  if($v->week_wap_flow>0&&$v->week_total_flow>0){
            //      $v->week_wap_flow_rate = round($v->week_wap_flow/$v->week_total_flow*100,2);
            //  }
 
            //  //PC转化率=销量/PC流量
            //  $v->pc_flow_rate = 0;
            //  if($v->week_pc_flow>0&&$v->sales_num>0){
            //     $v->pc_flow_rate = round($v->sales_num/$v->week_pc_flow*100,2);
            // }

            // //总转化率 = 销量/总流量
            // $v->all_flow_rate = 0;
            // if($v->week_total_flow>0&&$v->sales_num>0){
            //    $v->all_flow_rate = round($v->sales_num/$v->week_total_flow*100,2);
            // }

            // //上周总转化率
            // $v->last_all_flow_rate = 0;
            // if($lastweek_res->week_total_flow>0&&$lastweek_res->sales_num>0){
            //     $v->last_all_flow_rate = round($lastweek_res->sales_num/$lastweek_res->week_total_flow*100,2);
            // }

            // //总转化率与上周相比
            // $v->all_flow_rate_contrast = $v->all_flow_rate - $v->last_all_flow_rate;

            // //总转化率差异 = 总转化率-4
            // $v->all_flow_rate_dec = $v->all_flow_rate-4;
            
            //销售目标
            //销量
            if($lastweek_month_sales>0){
                $lastweek_sales_plan = ceil($lastweek_month_sales/4);
            }
            if($nextweek_month_sales>0){
                $nextweek_sales_plan = ceil($nextweek_month_sales/4);
            }
            if($week_month_sales>0){
                $week_sales_plan = ceil($week_month_sales/4);
            }


            //销售额
            if($lastweek_month_sales_total>0){
                $lastweek_sales_total_plan = ceil($lastweek_month_sales_total/4);
            }
            if($nextweek_month_sales_total>0){
                $nextweek_sales_total_plan = ceil($nextweek_month_sales_total/4);
            }
            if($week_month_sales_total>0){
                $week_sales_total_plan = ceil($week_month_sales_total/4);
            }





            
            //目标销量
            $v->sales_num_plan = $week_sales_plan;

            //下周销售目标
            $v->sales_num_plan_next =$nextweek_sales_plan;

            //销量完成率   销量/目标销量
            $v->sales_num_rate = 0;
            if($v->sales_num>0&&$v->sales_num_plan>0){
                $v->sales_num_rate = round(($v->sales_num/$v->sales_num_plan)*100,2);
            }


            // $v->sales_num_growth_rate = 0;
            // //销量涨幅率  这期销量-上期销量/上期销量
            // if($lastweek_res->sales_num>$v->sales_num){
            //     if(($lastweek_res->sales_num - $v->sales_num)>0&&$lastweek_res->sales_num>0){
            //         $v->sales_num_growth_rate = round((($lastweek_res->sales_num - $v->sales_num)/$lastweek_res->sales_num)*100,2);
            //         $v->sales_num_growth_rate =  0 - $v->sales_num_growth_rate;
            //     }
           
            // }else{
            //     if(($v->sales_num - $lastweek_res->sales_num)>0&&$lastweek_res->sales_num>0){
            //         $v->sales_num_growth_rate = round((($v->sales_num - $lastweek_res->sales_num)/$lastweek_res->sales_num)*100,2);
            //     }
              
            // }
        

            //目标销售额
            $v->sales_price_plan = $week_sales_total_plan;
            //下周销售目标
            $v->sales_price_plan_next = $nextweek_sales_total_plan;


            //销售额完成率  销售额/目标销售额
            $v->sales_price_rate  = 0;
            if($v->sales_price>0&&$v->sales_price_plan>0){
                $v->sales_price_rate = round(($v->sales_price/$v->sales_price_plan)*100,2);
            }

            //业绩是否完成
            $v->is_perform = 0;

            if($v->sales_price>$v->sales_price_plan){
                $v->is_perform = 1;
            }

            // //销售额涨幅率 这期销售额-上期销量/上期销售额
            // $v->sales_price_growth_rate = 0;
            // if($lastweek_res->sales_price>$v->sales_price){
            //     if(($lastweek_res->sales_price - $v->sales_price)>0&&$lastweek_res->sales_price>0){
            //         $v->sales_price_growth_rate = round((( $lastweek_res->sales_price - $v->sales_price)/$lastweek_res->sales_price)*100,2);
            //         $v->sales_price_growth_rate =  0 - $v->sales_price_growth_rate;
            //     }
           
            // }else{
            //     if(($v->sales_price - $lastweek_res->sales_price)>0&&$lastweek_res->sales_price>0){
            //         $v->sales_price_growth_rate = round((($v->sales_price - $lastweek_res->sales_price)/$lastweek_res->sales_price)*100,2);
            //     }
              
            // }


            //目标广告费
            $v->ad_price_plan = $week_ad;


            //ACOS与上周相比
            $v->acos_contrast = 0;
            //上周aocs
            $lastweek_acos = 0;
            $lastweek_tacos = 0;

            if($lastweek_res->ad_price>0&&$lastweek_res->ad_sales>0){
                $lastweek_acos = round(($lastweek_res->ad_price/$lastweek_res->ad_sales)*100,2);
            }
            if($lastweek_res->ad_price>0&&$lastweek_res->sales_price>0){
                $lastweek_tacos = round(($lastweek_res->ad_price/$lastweek_res->sales_price)*100,2);
            }

            $v->acos_contrast = round($v->acos - $lastweek_acos,2);

            
            //目标tacos
            $v->tacos_plan = 0;
 
            //TACOS是否超目标
            $v->is_tacos = 0;

            //TACOS与上周相比
            $v->tacos_contrast = 0;
            $v->tacos_contrast = round($v->tacos - $lastweek_tacos,2);

            //下周目标TACOS
            $v->tacos_plan_next = 0;

            // //库存数量
            // $v->fba_inventory = 0;
            // //库存于上周相比
            // $v->fba_inventory_contrast = 0;
            // //库存周转天数
            // $v->fba_inventory_day = 0;




        }


        $posttype = $params['posttype']??1;
        if($posttype==2){
            $p['title']='日报-fasin'.time();
            $p['title_list']  = [
                'fasin'=>'fasin',
                'cate_name'=>'分类',
                'shop_name'=>'店名',
                'sales_num'=>'销量',
                'sales_num_plan'=>'目标销量',
                'sales_num_plan_next'=>'下周销量目标',
                'sales_num_rate'=>'销量完成率',
                'acos'=>'acos',
                'tacos'=>'tacos',
                'acos_contrast'=>'acos与上周相比',
                'tacos_plan'=>'目标tacos',
                'is_tacos'=>'tacos是否超目标',
                'tacos_plan_next'=>'下周目标tacos',
                'sales_price'=>'销售额',
                'sales_price_plan'=>'目标销售额',
                'sales_price_rate'=>'销售额完成率',
                'sales_price_plan_next'=>'下周销售额目标',
                'is_perform'=>'业绩是否完成',
                'ad_price'=>'广告费用',
                'ad_price_plan'=>'目标广告费用',
                'ad_sales'=>'广告销售额',
                'cate_rank'=>'大类排名',
                'fba_inventory'=>'fba仓库存',
                'ad_num'=>'广告组数量',
                'ad_click_rate'=>'广告平均点击率',
                'ad_out_order'=>'广告出单',
                'week_total_flow'=>'本周总流量',
                'week_pc_flow'=>'本周PC流量',
                'week_wap_flow'=>'本周移动流量',
                'time'=>'中国时间',
                'u_time'=>'美国时间',
                'account'=>'运营',
                'pc_flow_rate'=>'PC转化率',
                'all_flow_rate'=>'总转化率',
                'active_assay'=>'本周活动、活动效果分析',
                'discount'=>'本周折扣',
                'problem'=>'本周问题',
                'next_plan'=>'下周计划',
                'task'=>'本周公共任务完成情况',
            ];

            // $this->excel_expord($p);
                
            $p['data'] =   $list;
            $p['user_id'] =$params['find_user_id']??1;
            $p['type'] = '日报-fasin-导出';
            $job = new \App\Http\Controllers\Jobs\ExcelTaskController;
            try {
                $job::runJob($p);
            } catch(\Exception $e){
                return ['type'=>'fail','msg'=>'加入队列失败'];
            }
            return ['type'=>'success','msg'=>'加入队列成功'];
        }

        return [
            'type' => 'success',
            'data' =>  $list,
            'totalNum' => $totalNum,
        ];


    }

    //周报列表
    public function DayReportTotal($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }
        $list = Db::table('amazon_day_report as a')->leftjoin('amazon_day_report_detail as b','a.id','=','b.report_id');
        // $arr = array();
        // $arr['user_id'] = $params['user_id'];
        // $arr['identity'] = array('day_report_total');
        // $powers = $this->powers($arr);

        // if(!$powers['day_report_list']){
        //     $list = $list->where('user_id',$params['user_id']);
        // }

        if(isset($params['find_user_id'])){
            $list->where('a.user_id',$params['find_user_id']);
        }

        if(isset($params['start_time'])&&isset($params['end_time'])){
            $start_time = $params['start_time'];
            $end_time = $params['end_time']." 23:59:59";
            $list = $list->whereBetween('a.ds', [$start_time, $end_time]);
        }

        //上周时间
        $lastweek_start = date("Y-m-d H:i:s",(strtotime($start_time)-(86400*7)));
        $lastweek_end = date("Y-m-d H:i:s",(strtotime($end_time)-(86400*7)));
        //获取上周月份
        $lastweek_moon = (int)date("m",strtotime($lastweek_start));
        //下周月份
        $nextweek_moon = (int)date("m",(strtotime($start_time)+(86400*7)));
        //本周月份
        $week_moon = (int)date("m",(strtotime($start_time)));

        if(isset($params['fasin'])){
            $details = Db::table('amazon_day_report_detail')->where('fasin',$params['fasin'])->groupBy('report_id')->get()->toArray();
            $ids  = array_column($details,'report_id');
            $list->whereIn('id',$ids);
        }

        $totalNum = $list->groupby('a.user_id')->get()->count();
        $list = $list->offset($page)->limit($limit)->select(DB::raw('GROUP_CONCAT(a.id) as ids'),DB::raw('sum(b.sales_num)as sales_num'),DB::raw('sum(b.sales_price)as sales_price'),DB::raw('sum(b.ad_price)as ad_price'),DB::raw('sum(b.ad_sales)as ad_sales'),DB::raw('sum(b.ad_click_rate)as ad_click_rate'),DB::raw('sum(b.ad_out_order)as ad_out_order'),DB::raw('sum(b.week_total_flow)as week_total_flow'),DB::raw('sum(b.week_pc_flow)as week_pc_flow'),DB::raw('sum(b.week_wap_flow)as week_wap_flow'),'user_id')->groupby('user_id')->get();

        foreach ($list as $v) {
            # code...
            $v->account = '';
            $v->account = $this->GetUsers($v->user_id)['account'];
            $v->acos = 0;
            $v->tacos = 0;
            if($v->ad_sales>0){
                //广告花费/广告销售额
                $v->acos = round(($v->ad_price/$v->ad_sales)*100,2);
            }
            if($v->sales_price>0){
                //广告花费/销售额
                $v->tacos = round(($v->ad_price/$v->sales_price)*100,2);
            }

            $ids =  explode(",",$v->ids);
            $v->link_num = 0;
            $v->detail = [];
            $v->fasin_codes = [];
            if($ids){
                $details = Db::table('amazon_day_report_detail')->whereIn('report_id',$ids)->groupBy('fasin')->get()->toarray();
                $v->link_num  = count($details);
                $fasin_codes = [];
                foreach ($details as $dv) {
                    # code...
                    $fasin_code = db::table('amazon_fasin_bind')->where('shop_id',$dv->shop_id)->where('fasin',$dv->fasin)->first();
                    if($fasin_code){
                        $fasin_codes[] = $fasin_code->fasin_code;
                    }
                }
                $v->fasin_codes = $fasin_codes;
            }




            //销量（月）
            $lastweek_month_sales = 0;
            $nextweek_month_sales = 0;
            $week_month_sales = 0;


            //销售额（月）
            $lastweek_month_sales_total = 0;
            $nextweek_month_sales_total = 0;
            $week_month_sales_total = 0;


            //销售目标（周）
            $lastweek_sales_plan = 0;
            $nextweek_sales_plan = 0;
            $week_sales_plan = 0;
            //销量（周）
            $lastweek_sales = 0;
            $nextweek_sales = 0;
            $week_sales = 0;

            //销售额目标（周）
            $lastweek_sales_total_plan = 0;
            $nextweek_sales_total_plan = 0;
            $week_sales_total_plan = 0;

            //销售额（周）
            $lastweek_sales_total = 0;
            $nextweek_sales_total = 0;
            $week_sales_total = 0;

            //广告花费(月)
            $lastweek_month_ad = 0;
            $nextweek_month_ad = 0;
            $week_month_ad = 0;

            //广告花费(周)
            $lastweek_ad = 0;
            $nextweek_ad = 0;
            $week_ad = 0;


            //获取计划数据
            if(!empty($v->fasin_codes)){
                $plan_res =  db::table('amazon_fasin_plan_info')->whereIn('fasin_code',$v->fasin_codes)->get();
                //上月$lastweek_moon  下月$nextweek_moon

                //销量字段
                $lastweekmonth_sales_word = 'month_sales'.$lastweek_moon;
                $nextweekmonth_sales_word = 'month_sales'.$nextweek_moon;
                $weekmonth_sales_word = 'month_sales'.$week_moon;


                //均价字段
                $lastweekmonth_price_word = 'month_price'.$lastweek_moon;
                $nextweekmonth_price_word = 'month_price'.$nextweek_moon;
                $weekmonth_price_word = 'month_price'.$week_moon;

                //广告花费字段ad_spend3
                $lastweekmonth_adspend_word = 'ad_spend'.$lastweek_moon;
                $nextweekmonth_adspend_word = 'ad_spend'.$nextweek_moon;
                $weekmonth_adspend_word = 'ad_spend'.$week_moon;

                if($plan_res){
                    foreach ($plan_res as $plv) {
                        # code...
                        //上月销量
                        $lastweek_month_sales+=$plv->$lastweekmonth_sales_word;
                        //上月销售额 = 上月销量*上月均价
                        $lastweek_month_sales_total += $plv->$lastweekmonth_sales_word * $plv->$lastweekmonth_price_word;
                        //上月广告花费
                        $lastweek_month_ad += $plv->$lastweekmonth_adspend_word;



                        //下月销量
                        $nextweek_month_sales+=$plv->$nextweekmonth_sales_word;
                        //下月销售额 = 下月销量*下月均价
                        $nextweek_month_sales_total += $plv->$nextweekmonth_sales_word * $plv->$nextweekmonth_price_word;
                        //下月广告花费
                        $nextweek_month_ad += $plv->$nextweekmonth_adspend_word;

                

                        //本月销量
                        $week_month_sales+=$plv->$weekmonth_sales_word;
                        //本月销售额 = 本月销量*本月均价
                        $week_month_sales_total += $plv->$weekmonth_sales_word * $plv->$weekmonth_price_word;
                        //本月广告花费
                        $week_month_ad += $plv->$weekmonth_adspend_word;

                    }
                }

            }


            //获取上周销售额 和销量

            $lastweek_res = db::table('amazon_day_report as a')->leftjoin('amazon_day_report_detail as b','a.id','=','b.report_id')->whereBetween('a.ds', [$lastweek_start, $lastweek_end])->where('a.user_id',$v->user_id)->select(DB::raw('GROUP_CONCAT(a.id) as ids'),DB::raw('sum(b.sales_num)as sales_num'),DB::raw('sum(b.sales_price)as sales_price'),DB::raw('sum(b.ad_price)as ad_price'),DB::raw('sum(b.ad_sales)as ad_sales'),DB::raw('sum(b.ad_click_rate)as ad_click_rate'),DB::raw('sum(b.ad_out_order)as ad_out_order'),DB::raw('sum(b.week_total_flow)as week_total_flow'),DB::raw('sum(b.week_pc_flow)as week_pc_flow'),DB::raw('sum(b.week_wap_flow)as week_wap_flow'))->get();
            $lastweek_res =  $lastweek_res[0];
            $v->lastweek_res = $lastweek_res;


            //本周广告平均率
            $v->ad_click_rate = 0;
            if($v->link_num>0&&$v->ad_click_rate>0){
                $v->ad_click_rate = round($v->ad_click_rate/$v->link_num,2);
            }

            $last_ids =  explode(",",$lastweek_res->ids);
            $last_link_num = 0;
            if($last_ids){
                $last_link_num = count($last_ids);
            }

             //上周广告平均率
            $v->last_ad_click_rate = 0;
            if($last_link_num>0&&$lastweek_res->ad_click_rate>0){
                $v->last_ad_click_rate = round($lastweek_res->ad_click_rate/$last_link_num,2);
            }

            //点击率与上周相比
            $v->ad_click_rate_contrast = $v->ad_click_rate - $v->last_ad_click_rate;

            //广告出单占比  广告出单/销量/
            $v->ad_out_order_rate = 0;
            if($v->ad_out_order>0&&$v->sales_num>0){
                $v->ad_out_order_rate = round($v->ad_out_order/$v->sales_num*100,2);
            }


            //上周广告出单占比  广告出单/销量/
            $v->last_ad_out_order_rate = 0;
            if($lastweek_res->ad_out_order>0&&$lastweek_res->sales_num>0){
                $v->last_ad_out_order_rate = round($lastweek_res->ad_out_order/$lastweek_res->sales_num*100,2);
            }

            //广告出单占比与上周相比
            $v->ad_out_order_rate_contrast =  round($v->ad_out_order_rate -  $v->last_ad_out_order_rate,2);

            //上周总流量
            $v->last_week_total_flow = $lastweek_res->week_total_flow;

            //总涨幅率  = 本周-上周 /上周
            $v->total_flow_rata = 0;
            if(($v->week_total_flow-$v->last_week_total_flow)>0&&$v->last_week_total_flow>0){
                $v->total_flow_rata = round(($v->week_total_flow-$v->last_week_total_flow)/$v->last_week_total_flow*100,2);
            }

            //pc流量占比 = pc流量/总流量
            $v->week_pc_flow_rate = 0;
            if($v->week_pc_flow>0&&$v->week_total_flow>0){
                $v->week_pc_flow_rate = round($v->week_pc_flow/$v->week_total_flow*100,2);
            }


             //移动流量占比 = 移动流量/总流量
             $v->week_wap_flow_rate = 0;
             if($v->week_wap_flow>0&&$v->week_total_flow>0){
                 $v->week_wap_flow_rate = round($v->week_wap_flow/$v->week_total_flow*100,2);
             }
 
             //PC转化率=销量/PC流量
             $v->pc_flow_rate = 0;
             if($v->week_pc_flow>0&&$v->sales_num>0){
                $v->pc_flow_rate = round($v->sales_num/$v->week_pc_flow*100,2);
            }

            //总转化率 = 销量/总流量
            $v->all_flow_rate = 0;
            if($v->week_total_flow>0&&$v->sales_num>0){
               $v->all_flow_rate = round($v->sales_num/$v->week_total_flow*100,2);
            }

            //上周总转化率
            $v->last_all_flow_rate = 0;
            if($lastweek_res->week_total_flow>0&&$lastweek_res->sales_num>0){
                $v->last_all_flow_rate = round($lastweek_res->sales_num/$lastweek_res->week_total_flow*100,2);
            }

            //总转化率与上周相比
            $v->all_flow_rate_contrast = $v->all_flow_rate - $v->last_all_flow_rate;

            //总转化率差异 = 总转化率-4
            $v->all_flow_rate_dec = $v->all_flow_rate-4;
            
            //销售目标
            //销量
            if($lastweek_month_sales>0){
                $lastweek_sales_plan = ceil($lastweek_month_sales/4);
            }
            if($nextweek_month_sales>0){
                $nextweek_sales_plan = ceil($nextweek_month_sales/4);
            }
            if($week_month_sales>0){
                $week_sales_plan = ceil($week_month_sales/4);
            }


            //销售额
            if($lastweek_month_sales_total>0){
                $lastweek_sales_total_plan = ceil($lastweek_month_sales_total/4);
            }
            if($nextweek_month_sales_total>0){
                $nextweek_sales_total_plan = ceil($nextweek_month_sales_total/4);
            }
            if($week_month_sales_total>0){
                $week_sales_total_plan = ceil($week_month_sales_total/4);
            }


            //广告花费
            if($lastweek_month_ad>0){
                $lastweek_ad = ceil($lastweek_month_ad/4);
            }
            if($nextweek_month_ad>0){
                $nextweek_ad = ceil($nextweek_month_ad/4);
            }
            if($week_month_ad>0){
                $week_ad = ceil($week_month_ad/4);
            }


            
            //目标销量
            $v->sales_num_plan = $week_sales_plan;

            //下周销售目标
            $v->sales_num_plan_next =$nextweek_sales_plan;

            //销量完成率   销量/目标销量
            $v->sales_num_rate = 0;
            if($v->sales_num>0&&$v->sales_num_plan>0){
                $v->sales_num_rate = round(($v->sales_num/$v->sales_num_plan)*100,2);
            }


            $v->sales_num_growth_rate = 0;
            //销量涨幅率  这期销量-上期销量/上期销量
            if($lastweek_res->sales_num>$v->sales_num){
                if(($lastweek_res->sales_num - $v->sales_num)>0&&$lastweek_res->sales_num>0){
                    $v->sales_num_growth_rate = round((($lastweek_res->sales_num - $v->sales_num)/$lastweek_res->sales_num)*100,2);
                    $v->sales_num_growth_rate =  0 - $v->sales_num_growth_rate;
                }
           
            }else{
                if(($v->sales_num - $lastweek_res->sales_num)>0&&$lastweek_res->sales_num>0){
                    $v->sales_num_growth_rate = round((($v->sales_num - $lastweek_res->sales_num)/$lastweek_res->sales_num)*100,2);
                }
              
            }

         

            $week_info = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$start_time)->where('end_time','>=',$start_time)->where('user_id',$v->user_id)->first();
          
            //本周活动、活动效果分析
            $v->active_assay = '';
            //本周折扣
            $v->discount = '';
            //本周问题
            $v->problem = '';
            //下周计划
            $v->next_plan = '';
            //本周公共任务完成情况
            $v->task = '';

            if($week_info){
                //本周活动、活动效果分析
                $v->active_assay = $week_info ->active_assay;
                //本周折扣
                $v->discount = $week_info ->discount;
                //本周问题
                $v->problem = $week_info ->problem;
                //下周计划
                $v->next_plan = $week_info ->next_plan;
                //本周公共任务完成情况
                $v->task = $week_info ->task;
            }


        

            //目标销售额
            $v->sales_price_plan = $week_sales_total_plan;
            //下周销售目标
            $v->sales_price_plan_next = $nextweek_sales_total_plan;


            //销售额完成率  销售额/目标销售额
            $v->sales_price_rate  = 0;
            if($v->sales_price>0&&$v->sales_price_plan>0){
                $v->sales_price_rate = round(($v->sales_price/$v->sales_price_plan)*100,2);
            }

            //业绩是否完成
            $v->is_perform = 0;


            //销售额涨幅率 这期销售额-上期销量/上期销售额
            $v->sales_price_growth_rate = 0;
            if($lastweek_res->sales_price>$v->sales_price){
                if(($lastweek_res->sales_price - $v->sales_price)>0&&$lastweek_res->sales_price>0){
                    $v->sales_price_growth_rate = round((( $lastweek_res->sales_price - $v->sales_price)/$lastweek_res->sales_price)*100,2);
                    $v->sales_price_growth_rate =  0 - $v->sales_price_growth_rate;
                }
           
            }else{
                if(($v->sales_price - $lastweek_res->sales_price)>0&&$lastweek_res->sales_price>0){
                    $v->sales_price_growth_rate = round((($v->sales_price - $lastweek_res->sales_price)/$lastweek_res->sales_price)*100,2);
                }
              
            }

            // $v->sales_price_growth_rate = round((($v->sales_price - $lastweek_res->sales_price)/$lastweek_res->sales_price)*100,2);


            //目标广告费
            $v->ad_price_plan = $week_ad;

            //ACOS与上周相比
            $v->acos_contrast = 0;
            
            //目标tacos
            $v->tacos_plan = 0;
 
            //TACOS是否超目标
            $v->is_tacos = 0;

            //TACOS与上周相比
            $v->tacos_contrast = 0;

            //下周目标TACOS
            $v->tacos_plan_next = 0;

            //库存数量
            $v->fba_inventory = 0;
            //库存于上周相比
            $v->fba_inventory_contrast = 0;
            //库存周转天数
            $v->fba_inventory_day = 0;


            //上周时间
            $v->time = [];
            $time['lastweek_start'] = $lastweek_start;
            $time['lastweek_end'] = $lastweek_end;
            $time['lastweek_moon'] = $lastweek_moon;
            $time['nextweek_moon'] = $nextweek_moon;
            $time['week_moon'] = $week_moon;
            $v->time = $time;
        }

        return [
            'type' => 'success',
            'data' =>  $list,
            'totalNum' => $totalNum,
        ];

    }



    //日报详情
    public function DayReportDetail($params){
        $id = $params['report_id']??0;
    
        $report = Db::table('amazon_day_report')->where('id',$id)->first();
        $fasin_list = Db::table('amazon_day_report_detail')->where('report_id',$id)->where('status',1);
        if(isset($params['one_cate_id'])){
            $fasin_list = $fasin_list->whereIn('one_cate_id',$params['one_cate_id']);
        }
        if(isset($params['two_cate_id'])){
            $fasin_list = $fasin_list->whereIn('two_cate_id',$params['two_cate_id']);
        }

        if(isset($params['three_cate_id'])){
            $fasin_list = $fasin_list->whereIn('three_cate_id',$params['three_cate_id']);
        }

        
        
        $fasin_list = $fasin_list->get();
        foreach ($fasin_list as $v) {
             # code...

             $weekinfo = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$report->ds)->where('end_time','>=',$report->ds)->where('fasin',$v->fasin)->first();

             $v->discount = '';
             $v->problem = '';
             $v->next_plan = '';
             $v->task = '';
             $v->active_assay = '';

             if($weekinfo){
                $v->discount = $weekinfo->discount;
                $v->problem = $weekinfo->problem;
                $v->next_plan = $weekinfo->next_plan;
                $v->task = $weekinfo->task;
                $v->active_assay = $weekinfo->active_assay;
   
             }


             if($v->fba_inventory==0){
                $skus = db::table('self_sku')->where('fasin',$v->fasin)->get()->toArray();
                $sku_ids = array_column($skus,'id');
                $product_detail = db::table('product_detail')->whereIn('sku_id',$sku_ids)->get()->toArray();
                $in_stock_num = array_column($product_detail,'in_stock_num');
                $in_bound_num = array_column($product_detail,'in_bound_num');
                $transfer_num = array_column($product_detail,'transfer_num');
                $in_stock_num = array_sum($in_stock_num);
                $in_bound_num = array_sum($in_bound_num);
                $transfer_num = array_sum($transfer_num);

                $fba_inventory = $transfer_num+$in_bound_num+$in_stock_num;
                $v->fba_inventory =  $fba_inventory;
                db::table('amazon_day_report_detail')->where('id',$v->id)->update(['fba_inventory'=>$fba_inventory]);

             }
             $v->account = '';
             $v->account = $this->GetUsers($report->user_id)['account'];
 
             //品名
             $v->cate_name = '';
             //店铺
             $v->shop_name =  $this->GetShop($v->shop_id)['shop_name'];
 
            //  $fasin_res = Redis::Hget('fasin_res', $v->fasin);
            //  if($fasin_res){
            //      $fasin_res = json_decode($fasin_res,true);
            //      //品名
            //      $v->cate_name = $fasin_res['cate_name'];
            //      //店铺
            //      // $v->shop_name = $fasin_res['shop_name'];
            //  }else{
            //     //  $spus = Db::table('product_detail as a')->leftjoin('self_sku as b','a.sellersku','=','b.sku')->leftjoin('self_spu as c','c.spu','=','b.spu')->where('a.parent_asin', $v->fasin)->select('b.sku','c.spu','c.type','c.one_cate_id','c.three_cate_id','b.shop_id')->get();
            //     //  $zspus = [];
            //     //  $zvspu = [];
            //     //  $catename = '';
            //     //  foreach ($spus as $sv) {
            //     //      # code...
 
            //     //      if($sv->one_cate_id>0){
            //     //          $one = $this->GetCategory($sv->one_cate_id)['name'];
            //     //          $three = $this->GetCategory($sv->three_cate_id)['name'];
            //     //          $catename = $one.$three;
            //     //      }elseif($sv->type==2){
            //     //          $zspus = Db::table('self_group_spu')->where('spu',$sv->spu)->get();
            //     //          foreach ($zspus as $zv) {
            //     //              # code...
            //     //              $zvspu = Db::table('self_spu')->where('spu',$zv->group_spu)->first();
            //     //              if($zvspu){
            //     //                 if($zvspu->one_cate_id>0){
            //     //                     $one = $this->GetCategory($zvspu->one_cate_id)['name'];
            //     //                     $three = $this->GetCategory($zvspu->three_cate_id)['name'];
            //     //                     $catename = $one.$three;
            //     //                     // $v->cate_name = $one.$three;
            //     //                 }
            //     //              }else{
            //     //                 $catename = '';
            //     //              }
       
            //     //          }
            //     //      }
            //     //  }
            //     //  $v->cate_name = $catename;
            //      $fasin =  $v->fasin;

            //      $spus = Db::table('self_sku as a')->leftjoin('self_spu as b','a.spu_id','=','b.id')->where('a.fasin',$fasin)->select('a.sku','b.spu','b.type','b.one_cate_id','b.three_cate_id','a.shop_id','b.id as spu_id')->get();
            //      $zspus = [];
            //      $zvspu = [];
            //      foreach ($spus as $sv) {
            //          # code...
            //        //   if($sv->shop_id>0){
            //        //      $shopname = $this->GetShop($sv->shop_id)['shop_name'];
            //        //   }
    
            //          if($sv->one_cate_id>0){
            //              $one = $this->GetCategory($sv->one_cate_id)['name'];
            //              $three = $this->GetCategory($sv->three_cate_id)['name'];
            //              $catename = $one.$three;
            //          }elseif($sv->type==2){
            //              $zspus = Db::table('self_group_spu')->where('spu_id',$sv->spu_id)->get();
            //              foreach ($zspus as $zv) {
            //                  # code...
            //                  $zvspu = Db::table('self_spu')->where('id',$zv->group_spu_id)->first();
            //                  if(!empty($zvspu)){
            //                      if($zvspu->one_cate_id>0){
            //                          $one = $this->GetCategory($zvspu->one_cate_id)['name'];
            //                          $three = $this->GetCategory($zvspu->three_cate_id)['name'];
            //                          $catename = $one.$three;
            //                          // $v->cate_name = $one.$three;
            //                      }
            //                  }
   
            //              }
            //          }
            //      }
                
            //      $v->cate_name = $catename;
            //      $set['cate_name'] = $catename;
            //    //   $set['shop_name'] = $shopname;
            //      Redis::Hset('fasin_res', $fasin, json_encode($set));
 
            //     //  $set['cate_name'] = $catename;
            //     //  $set['shop_name'] = $v->shop_name;
            //     //  Redis::Hset('fasin_res', $v->fasin, json_encode($set));
 
            //  }
            $fasins = db::table('amazon_fasin')->where('fasin',$v->fasin)->first();
            $v->cate_name  = '';
            if($fasins){
                $one = $this->GetCategory($fasins->one_cate_id)['name'];
                $three = $this->GetCategory($fasins->three_cate_id)['name'];
                $catename = $one.$three;
                $v->cate_name = $catename;
            }
            

 
 
             // if($sku){
             //     if(isset($sku->sku)){
             //         $v->sku = $sku->sku;
             //         $v->shop_name = $this->GetShop($sku->shop_id)['shop_name'];
             //         $spus = Db::table('self_spu')->where('spu',$sku->spu)->orwhere('old_spu',$sku->spu)->first();
             //         if($spus){
             //             $one = $this->GetCategory($spus->one_cate_id)['name'];
             //             $three = $this->GetCategory($spus->three_cate_id)['name'];
             //             $v->cate_name = $one.$three;
             //         }
             //     }
             // }
             
           
        }
        $report->fasin_list = $fasin_list;
     //    $data['report'] = $report;
     //    $data['fasin_list'] = $fasin_list; 
        return [
             'type' => 'success',
             'data' =>   $report
         ];
     }
 

     //获取日报本周内容
     public function GetDayReportWeekInfo($params){
        $ds = $params['ds'];
        $user_id = $params['user_id'];
        $res = db::table('amazon_day_report_weekinfo')->where('start_time','<=',$ds)->where('end_time','>=',$ds)->where('user_id',$user_id)->first();
        return [
            'type' => 'success',
            'data' =>   $res
        ];  
     }
 
     //获取上次填写日报
     public function GetLastReport($params){
         $fasin = [];
         $day = '';
         $user_id = $params['user_id']??0;
         $report = Db::table('amazon_day_report')->where('user_id',$user_id)->orderby('ds','DESC')->first();
         if($report){
             $ds = date('Y-m-d 00:00:00',time()-86400);
             $td = date('Y-m-d 00:00:00',time());
             if($report->ds != $ds&& $report->ds!=$td){
                $day = date('Y-m-d',strtotime($report->ds)+86400);
             }

             $fasin_list = Db::table('amazon_day_report_detail')->where('report_id',$report->id)->where('status',1)->get()->toArray();
             if($fasin_list){
                 // $fasin  = array_column($fasin_list,'fasin');
                 $i = 0;
                 foreach ($fasin_list as $f) {
                     # code...
                     $fasin[$i]['fasin'] = $f->fasin;
                     $fasin[$i]['shop_id'] = $f->shop_id;
                     $i++;
                 }
             }
         }
 
         $returns['fasin'] = $fasin;
         $returns['day'] = $day;
         return [
              'type' => 'success',
              'data' =>  $returns
          ];
     }
 
 
 
     // `ds` datetime DEFAULT NULL,
     // `user_id` int DEFAULT NULL,
     // `sales_num` int DEFAULT '0' COMMENT '销量',
     // `sales_price` double(11,2) DEFAULT NULL COMMENT '销售额',
     // `ad_price` double(11,2) DEFAULT NULL COMMENT '广告花费',
     // `ad_sales` double(11,2) DEFAULT NULL COMMENT '广告销售额',
     // `acos` double(11,2) DEFAULT NULL COMMENT 'Acos',
     // `tacos` double(11,2) DEFAULT NULL COMMENT 'Tacos',
     // `link_num` int DEFAULT NULL COMMENT '在售链接数量',
     // `oa` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT 'oa建议',
     // `difficulty` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '困难',
 
     // `fasin` varchar(255) DEFAULT NULL,
     // `sales_num` int DEFAULT '0' COMMENT '销量',
     // `acos` double(11,2) DEFAULT NULL COMMENT 'ACOS',
     // `tacos` double(11,2) DEFAULT NULL COMMENT 'TACOS',
     // `cate_rank` int DEFAULT NULL COMMENT '大类排名',
 
     //日报
     public function DayReport($params){
         $ds = date('Y-m-d 00:00:00',time());
         if(isset($params['ds'])){
             $ds =  $params['ds']." 00:00:00";
         }
 
         $user_id = $params['user_id'];
         $id =  $params['id']??0;
         $is_in = Db::table('amazon_day_report')->where('ds',$ds)->where('user_id',$user_id)->first();
         if($is_in){
             $id = $is_in->id;
         }
         $sales_num = $params['sales_num']??0;//销量
         $sales_price = $params['sales_price']??0;//销售额
         $ad_price = $params['ad_price']??0;//广告花费
         $ad_sales = $params['ad_sales']??0;//广告销售额
         $acos = $params['acos']??0;//acos  广告花费/销售额
         $tacos = $params['tacos']??0;//tacos 广告花费/广告销售额
         $oa = $params['oa']??'无';
         $ad_num = $params['ad_num']??0;
         $difficulty = $params['difficulty']??'无';
 
         $task_insert['ds'] = $ds;
         $task_insert['user_id'] = $user_id;
         $task_insert['sales_num'] = $sales_num;
         $task_insert['sales_price'] = $sales_price;
         $task_insert['ad_price'] = $ad_price;
         $task_insert['ad_sales'] = $ad_sales;
         $task_insert['ad_num'] = $ad_num;
         $task_insert['acos'] = $acos;
         $task_insert['tacos'] = $tacos;
         $task_insert['oa'] = $oa;
         $task_insert['difficulty'] = $difficulty;
         $task_insert['link_num']  = 0;
         $task_insert['holiday']  =  $params['holiday']??0;
         





         if(is_array($params['fasin_list'])){
             $task_insert['link_num'] = count($params['fasin_list']);
         }
         if($id<=0){
             $report_id = Db::table('amazon_day_report')->insertGetId($task_insert);
         }else{
             $report_id = $id;
             Db::table('amazon_day_report')->where('id',$id)->update($task_insert);
             Db::table('amazon_day_report_detail')->where('report_id',$id)->delete();
         }
 
         if(isset($params['fasin_list'])){
             $fasin_list = $params['fasin_list'];
             foreach ($fasin_list as  $fasins) {
                 # code...
                 $week_insert = [];
                 $fasin = $fasins['fasin'];
                 if($fasin){


                    
                    //周计划
                    $week_insert['user_id'] =$user_id;

                    if(!empty($fasins['active_assay'])&&!empty($fasins['discount'])&&!empty($fasins['problem'])&&!empty($fasins['next_plan'])){
                        $week_insert['active_assay'] = $fasins['active_assay']??'';
                        $week_insert['discount'] = $fasins['discount']??'';
                        $week_insert['problem'] = $fasins['problem']??'';
                        $week_insert['next_plan'] = $fasins['next_plan']??'';
                        $week_insert['task'] = $fasins['task']??'';
                        $week_insert['fasin'] = $fasin;
    
    
                        $t_t = strtotime($ds);
                        $this_week_num = date('w',$t_t);
                        if($this_week_num==0){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t-(86400*6)); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t); }
                        if($this_week_num==1){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t +(86400*6)); }
                        if($this_week_num==2){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t-86400); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t+(86400*5)); }
                        if($this_week_num==3){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t -(86400*2)); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t +(86400*4)); }
                        if($this_week_num==4){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t -(86400*3)); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t +(86400*3)); }
                        if($this_week_num==5){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t -(86400*4)); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t +(86400*2)); }
                        if($this_week_num==6){  $week_insert['start_time']=date('Y-m-d 00:00:00',$t_t -(86400*5)); $week_insert['end_time']=date('Y-m-d 23:59:59',$t_t +86400); }
    
                        $weeks = db::table('amazon_day_report_weekinfo')->where('fasin', $fasin)->where('start_time', $week_insert['start_time'])->where('end_time', $week_insert['end_time'])->first();
    
    
                        if($weeks){
                            db::table('amazon_day_report_weekinfo')->where('id',$weeks->id)->update($week_insert);
                        }else{
                            db::table('amazon_day_report_weekinfo')->insert($week_insert);
                        }
    
                    }

                   

                    //  $detail_id =  $fasins['id']??0;
                     $cate_rank = $fasins['cate_rank']??0;//大类排名
                     $detail_insert['fasin'] = $fasin;
                     $detail_insert['sales_num'] = $fasins['sales_num']??0;
                     $detail_insert['sales_price'] = $fasins['sales_price']??0;
                     $detail_insert['ad_price'] = $fasins['ad_price']??0;
                     $detail_insert['ad_sales'] = $fasins['ad_sales']??0;
                     $detail_insert['ad_num'] = $fasins['ad_num']??0;
                     $detail_insert['acos'] = $fasins['acos']??0;
                     $detail_insert['tacos'] = $fasins['tacos']??0;
                     $detail_insert['cate_rank'] = $cate_rank;
                     $detail_insert['report_id'] = $report_id;
                     $detail_insert['shop_id'] = $fasins['shop_id']??0;
                     $detail_insert['fba_inventory'] = $fasins['fba_inventory']??0;
                     $detail_insert['status'] = 1;
                     $detail_insert['one_cate_id'] = 0;
                     $detail_insert['two_cate_id'] = 0;
                     $detail_insert['three_cate_id'] = 0;


                     $detail_insert['ad_click_rate']  =  $fasins['ad_click_rate']??0;
                     $detail_insert['ad_out_order']  =  $fasins['ad_out_order']??0;
                     $detail_insert['week_total_flow']  =  $fasins['week_total_flow']??0;
                     $detail_insert['week_pc_flow']  =  $fasins['week_pc_flow']??0;
                     $detail_insert['week_wap_flow']  =  $fasins['week_wap_flow']??0;



                     $detail_insert['week_total_flow']  = 0;
                     $detail_insert['week_pc_flow']  =  0;
                     $detail_insert['week_wap_flow']  =  0;


                     $detail_insert['pc_flow_rate']= 0;
                     $detail_insert['all_flow_rate'] = 0;
                    //PC转化率=销量/PC流量
                    if($detail_insert['week_pc_flow']>0&&$detail_insert['sales_num']>0){
                        $detail_insert['pc_flow_rate'] = round($detail_insert['sales_num']/$detail_insert['week_pc_flow']*100,2);
                    }

                    //总转化率 = 销量/总流量
                    if($detail_insert['week_total_flow']>0&&$detail_insert['sales_num']>0){
                        $detail_insert['all_flow_rate'] = round($detail_insert['sales_num']/$detail_insert['week_total_flow']*100,2);
                    }

                     $yes_ds = date('Y-m-d',strtotime($ds)-86400);
                     if(($fasins['week_total_flow']+$fasins['week_wap_flow']+$fasins['week_pc_flow'])>0){
                        $yestoday_report = db::table('amazon_day_report_detail as a')->leftjoin('amazon_day_report as b','a.report_id','=','b.id')->where('a.fasin',$fasin)->where('b.ds','like','%'.$yes_ds.'%')->select('a.id')->first();
                        if($yestoday_report){
                            // return['type'=>'fail','msg'=>'昨日无此fasin，无法填写昨日流量'.$fasin.'-时间-'.$yes_ds.'-用户-'.$user_id];
                            $detail_up['week_total_flow']  =  $fasins['week_total_flow']??0;
                            $detail_up['week_pc_flow']  =  $fasins['week_pc_flow']??0;
                            $detail_up['week_wap_flow']  =  $fasins['week_wap_flow']??0;
                            db::table('amazon_day_report_detail')->where('id',$yestoday_report->id)->update($detail_up);
                        }

                     }
 



                     $fasin_cates = db::table('amazon_fasin')->where('fasin',$fasin)->first();
                     if($fasin_cates){
                        $detail_insert['one_cate_id'] = $fasin_cates->one_cate_id;
                        $detail_insert['two_cate_id'] = $fasin_cates->two_cate_id;
                        $detail_insert['three_cate_id'] = $fasin_cates->three_cate_id;
                     }
                    
                     Db::table('amazon_day_report_detail')->insert($detail_insert);
                    //  if($detail_id<=0){
                      
                    //  }else{
                    //      Db::table('amazon_day_report_detail')->where('id',$detail_id)->update($detail_insert);
                    //  }
                 }
             }
         }
 
         return ['type' => 'success', 'msg' => '操作成功'];
 
     }


     //自动填写日报
     public function ReportAutoM($params){
        $ds = $params['ds']??date('Y-m-d',time());
        $yds = date('Y-m-d',strtotime($ds)-86400);
        $yyds = date('Y-m-d',strtotime($ds)-(86400*2));
        $user_id = $params['user_id'];

        //获取有归属的用户

        $amazon_fasin = db::table('amazon_fasin')->where('user_id',$user_id)->get();

        if(!$amazon_fasin->isNotEmpty()){
            return ['type' => 'fail', 'msg' => '该用户无fasin'];
        }

        $fasins = [];
        $o_sales_num = 0;
        $o_sales_price = 0;
        $o_ad_price = 0;
        $o_ad_sales = 0;
        $o_ad_num = 0;
        $fasin_list = [];
        foreach ($amazon_fasin as $v) {
            # code...
            $shops = explode(',',$v->shops);
            foreach ($shops as $shop_id) {
                $skus = db::table('self_sku')->where('shop_id',$shop_id)->where('fasin',$v->fasin)->get()->toArray();
                $sku_ids = array_column($skus,'id');
                if(empty($sku_ids)){
                    continue;
                }
                $items = Db::table('amazon_order_item')->where('order_status','!=','Canceled')->whereIn('sku_id',$sku_ids)->where('amazon_time','like','%'.$yds.'%')->get();
    

                //销量销售额
                $sales_num = 0;
                $sales_price = 0;
                foreach ($items as $iv) {
                    # code...
                    $sales_num += $iv->quantity_ordered;
                    if($iv->amount>0){
                        $sales_price += $iv->quantity_ordered * $iv->amount;
                    }else{
                        $price = Db::table('product_detail')->where('sku_id',$iv->sku_id)->first();
                        $pris = 0;
                        if($price){
                            $pris = $price->price;
                        }
                        $sales_price +=  $iv->quantity_ordered *$pris;
                    }
                }
        
                //fba库存
                $product = Db::table('product_detail')->whereIn('sku_id',$sku_ids)->get()->toArray();

                $in_bound_num = array_sum(array_column($product,'in_bound_num'));
                $in_stock_num = array_sum(array_column($product,'in_stock_num'));
                $transfer_num = array_sum(array_column($product,'transfer_num'));
       
                $fba_inventory = $in_bound_num + $in_stock_num + $transfer_num;

                //分类排名
                $num = 0;
                //  $ds = date('Y-m-d 00:00:00',time()-86400);
                 $rank = Db::table('amazon_link_ranklog')->where('father_asin',$v->fasin)->orderby('ds','DESC')->first();
                 if($rank){
                     $num = $rank->all_num;
                 }
       
                $fasins['fasin'] = $v->fasin;
                $fasins['shop_id'] = $shop_id;
                $fasins['sales_num'] = $sales_num;
                $fasins['sales_price'] = round($sales_price,2);
                $fasins['fba_inventory'] = $fba_inventory;
                $fasins['cate_rank'] = $num;

                 //广告数据
                $ad_res = db::table('lingxing_ad_campaign as a')->leftjoin('lingxing_ad_campaign_report as b','a.campaign_id','=','b.campaign_id')->where('a.portfolio_name','like','%'.$v->fasin.'%')->where('b.report_date',$yds)->where('b.shop_id',$shop_id)->get();
                 //广告组数量
                $ad_num = 0;
                //广告花费
                $ad_price = 0;
                //广告销售额
                $ad_sales = 0;
                //广告出单
                $ad_out_order = 0;
                //点击率
                $clicks = 0;
                $impressions = 0;
                $ad_click_rate = 0;
                foreach ($ad_res as $adv) {
                    # code...
                    $ad_num+=1;
                    $ad_price += $adv->cost;
                    $ad_sales +=  $adv->sales;
                    $ad_out_order +=$adv->units;
                    $clicks +=$adv->clicks;
                    $impressions +=$adv->impressions;

                }
                if($impressions>0){
                    $ad_click_rate = round(($clicks/ $impressions)*100,2);
                }
                $fasins['ad_num'] = $ad_num;
                $fasins['ad_price'] = $ad_price;
                $fasins['ad_sales'] = $ad_sales;
                $fasins['ad_out_order'] = $ad_out_order;
                $fasins['ad_click_rate'] = $ad_click_rate;
                //获取流量
                $l_expression = db::table('lingxing_product_expression')->where('fasin',$v->fasin)->where('shop_id',$shop_id)->where('date',$yyds)->first();
                
                $fasins['week_total_flow'] = 0;
                $fasins['week_pc_flow'] = 0;
                $fasins['week_wap_flow'] = 0;
                if($l_expression){
                    $fasins['week_total_flow'] = $l_expression->sessions_total;
                    $fasins['week_pc_flow'] =  $l_expression->sessions;
                    $fasins['week_wap_flow'] =  $l_expression->sessions_mobile;
                }

                $fasins['ds'] = $ds;
                $fasins['acos'] = 0;    
                $fasins['tacos'] = 0;
                //acos  广告花费/广告销售额
    
                if($fasins['ad_sales']>0){
                    $fasins['acos'] = round(($fasins['ad_price']/$fasins['ad_sales'])*100,2);
                }
    
                //tacos 广告花费/销售额
                if($fasins['sales_price']>0){
                    $fasins['tacos'] = round(($fasins['ad_price']/$fasins['sales_price'])*100,2);
                }

                $o_sales_num +=(int)$fasins['sales_num'];
                $o_sales_price +=(int)$fasins['sales_price'];
                $o_ad_price +=(int)$fasins['ad_price'];
                $o_ad_sales +=(int)$fasins['ad_sales'];
                $o_ad_num +=(int)$fasins['ad_num'];

                $fasin_list[] = $fasins;
            }

          
        }

        if(empty($fasin_list)){
            return ['type'=>'fail','msg'=>'无数据'];
        }

        //汇总单人日报
        $acos = 0;
        $tacos = 0;

        if($o_ad_price>0&&$o_sales_price>0){
            $acos = round(($o_ad_price/$o_sales_price)*100,2);
        }

        //tacos 广告花费/销售额
        if($o_ad_price>0&&$o_sales_price>0){
            $tacos = round(($o_ad_price/$o_sales_price)*100,2);
        }

        $one_data['sales_num'] =  $o_sales_num;
        $one_data['sales_price'] =  $o_sales_price;
        $one_data['ad_price'] =  $o_ad_price;
        $one_data['ad_sales'] =  $o_ad_sales;
        $one_data['ad_num'] =  $o_ad_num;
        $one_data['fasin_list'] =  $fasin_list;
        $one_data['user_id'] =  $user_id;
        $one_data['ds'] =  $ds;
   
    
        $msg = $this->DayReport($one_data);
        if($msg['type']!='success'){
            // db::rollback();// 回调
            return ['type'=>'fail','msg'=>$msg['msg']];
        }

        return ['type' => 'success', 'data' => $one_data];
     }
     

     //确认日报
     public function ConfirmDayreport($params){
        db::table('amazon_day_report')->where('id',$params['id'])->update(['status'=>1]);

        return ['type' => 'success', 'msg' => '确认成功'];
     }



     //日报导入
     public function ReportExcelImportM($params){
        $p['row'] = ['shop_id','fasin','sales_num','sales_price','ad_price','ad_sales','ad_num','ad_click_rate','ad_out_order','week_total_flow','week_pc_flow','week_wap_flow','ds','active_assay','discount','problem','next_plan','task'];
        $p['file'] = $params['file'];
        $p['start'] = 2;
        $data =  $this->CommonExcelImport($p);

        // return['type'=>'success','data'=> $data];
        $ds_arr = [];
        foreach ($data as &$v) {
            # code...
            $rank = Db::table('amazon_link_ranklog')->where('father_asin',$v['fasin'])->where('ds','like','%'.$v['ds'].'%')->first();
            $v['cate_rank'] = 0;
            if($rank){
                $v['cate_rank'] = $rank->cate_num;
            }

            $v['acous'] = 0;    
            $v['tacous'] = 0;
            //acos  广告花费/广告销售额

            if($v['ad_price']>0&&$v['ad_sales']>0){
                $v['acos'] = round(($v['ad_price']/$v['ad_sales'])*100,2);
            }

            //tacos 广告花费/销售额
            if($v['ad_price']>0&&$v['sales_price']>0){
                $v['tacos'] = round(($v['ad_price']/$v['sales_price'])*100,2);
            }

            $ds_arr[$v['ds']] = [];

        }


        // return['type'=>'success','data'=> $data];
        foreach ($data as $vd) {
            # code...
            $ds = $vd['ds'];
            $ds_arr[$ds][] = $vd;
        }

        // return['type'=>'success','data'=> $ds_arr];


        $newdata = [];
        foreach ($ds_arr as $day => $v) {
            # code...
            $one_data['ds'] = $day;
            $one_data['user_id'] = $params['user_id']??0;
            $o_sales_num = 0;
            $o_sales_price = 0;
            $o_ad_price = 0;
            $o_ad_sales = 0;
            $o_ad_num = 0;

            $acos = 0;
            $tacos = 0;
            foreach ($v as $vv) {
                # code...
                $o_sales_num +=(int)$vv['sales_num'];
                $o_sales_price +=(int)$vv['sales_price'];
                $o_ad_price +=(int)$vv['ad_price'];
                $o_ad_sales +=(int)$vv['ad_sales'];
                $o_ad_num +=(int)$vv['ad_num'];
            }



             //acos  广告花费/广告销售额

            if($o_ad_price>0&&$o_sales_price>0){
                $acos = round(($o_ad_price/$o_sales_price)*100,2);
            }

            //tacos 广告花费/销售额
            if($o_ad_price>0&&$o_sales_price>0){
                $tacos = round(($o_ad_price/$o_sales_price)*100,2);
            }
            $one_data['sales_num'] =  $o_sales_num;
            $one_data['sales_price'] =  $o_sales_price;
            $one_data['ad_price'] =  $o_ad_price;
            $one_data['ad_sales'] =  $o_ad_sales;
            $one_data['ad_num'] =  $o_ad_num;

            $one_data['fasin_list'] = $v;

            $newdata[] =  $one_data;
        }


        db::beginTransaction();    //开启事务
        foreach ($newdata as $v) {
            # code...
            $msg = $this->DayReport($v);
            if($msg['type']!='success'){
                db::rollback();// 回调
                return ['type'=>'fail','msg'=>$msg['msg']];
            }
        }

        db::commit();
        return ['type'=>'success','msg'=>'添加成功','data'=>$newdata];
     }
 
     public function GetSpuInventoryByBaseSpu($params){
        $spu = $params['spu'];
        $base_spu_id =$this->GetBaseSpuIdBySpu($spu);
        $return = [];
        $return['e_fba'] = 0;
        $return['e_here'] = 0;
        $return['u_fba'] = 0;
        $return['u_here'] = 0;
        $return['img'] = '';
        $ds = date('Y-m-d',time());
        if($base_spu_id){
            $return['img'] = $this->GetBaseSpuImg($base_spu_id);
            $spus = db::table('self_spu')->where('base_spu_id',$base_spu_id)->get();
            foreach ($spus as $v) {
                # code...
                if($v->market=='E'){
                    $e_res = db::table('cache_spu')->where('spu_id',$v->id)->where('ds','like', "{$ds}%")->first();
                    $return['e_fba'] = $e_res->in_stock_num+$e_res->transfer_num+$e_res->in_bound_num;
                    $return['e_here'] = $e_res->quanzhou_num+$e_res->tongan_num+$e_res->cloud_num+$e_res->factory_num;

                }elseif($v->market=='U'){
                    $u_res = db::table('cache_spu')->where('spu_id',$v->id)->where('ds','like', "{$ds}%")->first();
                    $return['u_fba'] = $u_res->in_stock_num+$u_res->transfer_num+$u_res->in_bound_num;
                    $return['u_here'] = $u_res->quanzhou_num+$u_res->tongan_num+$u_res->cloud_num+$u_res->factory_num;
                }
            }
        }
        

        return ['type'=>'success','data'=>$return];

     }
 
     //获取链接排名
     public function GetRankByFasin($params){
         $fasin = $params['fasin'];
         $is_fasin = Db::table('amazon_fasin')->where('fasin', $fasin)->first();

         if(!$is_fasin){
             return ['type' => 'fail','msg' => '无此fasin信息,请先去fasin报表添加'];
         }
        //  $skus  = array_column($is_fasin,'sellersku');
 
 
         $skulist = Db::table('self_sku')->where('fasin',$fasin)->get()->toArray();
 
         $skushop = [];
         $orders = [];
         $sales_price = [];
         $sps = [];
         $adData = [];
         foreach ($skulist as $v) {
             # code...
             $sps[$v->shop_id] = $v->shop_id;
             $sales_price[$v->shop_id] = 0;
             $orders[$v->shop_id] = 0;
             $skushop[$v->shop_id][] = $v->id;

             //广告数据
             $adData[$v->shop_id] = [
                 'ad_num'      => 0,
                 'cost'        => 0,
                 'sales'       => 0,
                 'orders'      => 0,
                 'impressions' => 0,
                 'clicks'      => 0,
                 'ctr'         => 0,
             ];
         }
 
         $shops = [];
         $shop_name = [];
         foreach ($sps as $k) {
             # code...
             $shops[] = $this->GetShop($k);
             $shop_name[$k] = $this->GetShop($k)['shop_name'];
         }
 
         
 
         $ids  = array_column($skulist,'id');

 
         $time = date('Y-m-d 00:00:00',time()-86400);

         if(isset($params['time'])){
            $time = $params['time'];

            $time = date('Y-m-d',strtotime($time)-86400);
         }
        //  DB::connection()->enableQueryLog();
         // sum('quantity_ordered') amount
         $items = Db::table('amazon_order_item')->whereIn('sku_id',$ids)->where('order_status','!=','Canceled')->where('amazon_time','like','%'.$time.'%')->get();
        //  var_dump(DB::getQueryLog());
 
         $product = Db::table('product_detail')->whereIn('sku_id',$ids)->get()->toArray();

         $in_bound_num = array_sum(array_column($product,'in_bound_num'));
         $in_stock_num = array_sum(array_column($product,'in_stock_num'));
         $transfer_num = array_sum(array_column($product,'transfer_num'));

         $fba_inventory = $in_bound_num + $in_stock_num + $transfer_num;

         
        
         $new_order=[];
         $i = 0;
         foreach ($items as $v) {
             # code...
             $new_order[$i]['amazon_order_id'] =  $v->amazon_order_id;
             $new_order[$i]['order_item_id'] =  $v->order_item_id;
             $new_order[$i]['quantity_ordered'] =  $v->quantity_ordered;
             $new_order[$i]['is_order'] = 1;
             $new_order[$i]['sku'] = $v->seller_sku;
             $new_order[$i]['sku_id'] = $v->sku_id;
 
             foreach ($skushop as $shop_id => $shop_skus) {
                 # code...
                 $new_order[$i]['shop_id'] = $shop_id;
                 foreach ($shop_skus as $shop_sku) {
                     # code...
                     if($v->sku_id==$shop_sku){
                         $orders[$shop_id]+= $v->quantity_ordered;
                         if($v->amount>0){
                             $sales_price[$shop_id] += $v->quantity_ordered * $v->amount;
                         }else{
                            //  $skus = $this->GetSku($v->seller_sku);
                             $new_order[$i]['is_order'] = 0;
                             $price = Db::table('product_detail')->where('sku_id',$v->sku_id)->first();
                            //  if(isset($skus['old_sku'])){
                            //      $price =  $price->orwhere('sellersku',$skus['old_sku']);
                            //  }
                             $pris = 0;
                             if($price){
                                 $pris = $price->price;
                             }

                             $v->amount = $pris;
                             $sales_price[$shop_id] += $v->quantity_ordered *$pris;
                         }
                         $sales_price[$shop_id] = round($sales_price[$shop_id],2);
                         $new_order[$i]['amount'] =   $v->amount;
                     }
                 }
             }
 
     
             $i++;
 
         }
         // $sales_price = round($sales_price,2);
         $num = 0;
        //  $ds = date('Y-m-d 00:00:00',time()-86400);
         $rank = Db::table('amazon_link_ranklog')->where('father_asin',$fasin)->orderby('ds','DESC')->first();
         if($rank){
             $num = $rank->all_num;
         }
 
         //品名
         $catename = '';
         // //店铺
         // $shopname = '';
 
          $fasin_res = Redis::Hget('fasin_res',$fasin);
          if($fasin_res){
              $fasin_res = json_decode($fasin_res,true);
              //品名
              $catename = $fasin_res['cate_name'];
             //  //店铺
            //   $shopname  = $fasin_res['shop_name'];
          }else{
              $spus = Db::table('self_sku as a')->leftjoin('self_spu as b','a.spu_id','=','b.id')->where('a.fasin',$fasin)->select('a.sku','b.spu','b.type','b.one_cate_id','b.three_cate_id','a.shop_id','b.id as spu_id')->get();
              $zspus = [];
              $zvspu = [];
              foreach ($spus as $sv) {
                  # code...
                //   if($sv->shop_id>0){
                //      $shopname = $this->GetShop($sv->shop_id)['shop_name'];
                //   }
 
                  if($sv->one_cate_id>0){
                      $one = $this->GetCategory($sv->one_cate_id)['name'];
                      $three = $this->GetCategory($sv->three_cate_id)['name'];
                      $catename = $one.$three;
                  }elseif($sv->type==2){
                      $zspus = Db::table('self_group_spu')->where('spu_id',$sv->spu_id)->get();
                      foreach ($zspus as $zv) {
                          # code...
                          $zvspu = Db::table('self_spu')->where('id',$zv->group_spu_id)->first();
                          if(!empty($zvspu)){
                              if($zvspu->one_cate_id>0){
                                  $one = $this->GetCategory($zvspu->one_cate_id)['name'];
                                  $three = $this->GetCategory($zvspu->three_cate_id)['name'];
                                  $catename = $one.$three;
                                  // $v->cate_name = $one.$three;
                              }
                          }

                      }
                  }
              }
             
 
              $set['cate_name'] = $catename;
            //   $set['shop_name'] = $shopname;
              Redis::Hset('fasin_res', $fasin, json_encode($set));
 
          }
 
         // //品名
         // $catename = '';
         // //店铺
         // $shopname = '';
         // $sku = Db::table('product_detail as a')->leftjoin('self_sku as b','a.sellersku','=','b.sku')->where('a.parent_asin',$fasin)->select('b.sku','b.shop_id','b.spu')->first();
         // if($sku){
         //     if(isset($sku->sku)){
         //         $shopname = $this->GetShop($sku->shop_id)['shop_name'];
         //         $spus = Db::table('self_spu')->where('spu',$sku->spu)->orwhere('old_spu',$sku->spu)->first();
         //         if($spus){
         //             $one = $this->GetCategory($spus->one_cate_id)['name'];
         //             $three = $this->GetCategory($spus->three_cate_id)['name'];
         //             $catename = $one.$three;
         //         }
         //     }
         // }

         //获取广告数据
         $campaignId = DB::table('lingxing_ad_campaign')
             ->where('portfolio_name', 'like', $fasin . '%')
             ->pluck('campaign_id');


         $list = DB::table('lingxing_ad_campaign_report')
             ->where('report_date', date('Y-m-d', strtotime('-1 days',strtotime($params['time']))))
             ->whereIn('campaign_id', $campaignId)
             ->get();


//         $adData = [];
         foreach ($list as $value) {
             if (!isset($adData[$value->shop_id])) {
                 $adData[$value->shop_id]['ad_num']      = 1;
                 $adData[$value->shop_id]['cost']        = $value->cost;
                 $adData[$value->shop_id]['sales']       = $value->sales;
                 $adData[$value->shop_id]['orders']      = $value->orders;
                 $adData[$value->shop_id]['impressions'] = $value->impressions;
                 $adData[$value->shop_id]['clicks']      = $value->clicks;
             } else {
                 $adData[$value->shop_id]['ad_num']      += 1;
                 $adData[$value->shop_id]['cost']        += $value->cost;
                 $adData[$value->shop_id]['sales']       += $value->sales;
                 $adData[$value->shop_id]['orders']      += $value->orders;
                 $adData[$value->shop_id]['impressions'] += $value->impressions;
                 $adData[$value->shop_id]['clicks']      += $value->clicks;
             }
         }

         foreach ($adData as $key => $value) {
             $adData[$key]['cost']  = round($value['cost'], 2);
             $adData[$key]['sales'] = round($value['sales'], 2);
             $adData[$key]['ctr']   = $value['impressions'] ? round(($value['clicks'] / $value['impressions']) * 100, 2) : 0;
         }

         return [
             'sales_num'     => $orders,
             'cate_rank'     => $num,
             'sales_price'   => $sales_price,
             'shop_name'     => $shop_name,
             'cate_name'     => $catename,
             'order'         => $new_order,
             'skushop'       => $skushop,
             'shops'         => $shops,
             'fba_inventory' => $fba_inventory,
             'ad_data'       => $adData,
         ];
     }
 


    public function GetFasin($params){
       
        $fasin_list = Db::table('amazon_fasin');
        if(isset($params['fasin'])){
            $fasin = $params['fasin'];
            $fasin_list  = $fasin_list->where('fasin', 'like', '%' . $fasin . '%');
        }
        $fasin_list = $fasin_list->get();
        return ['data'=> $fasin_list];
    }

    



    //供应链导入
    public function SupplyChainImport($params)
    {

        ////获取Excel文件数据
        $user_id = $params['user_id'];
        // $supply_time = $params['supply_time']??time();
        $file = $params['file'];

        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        if ($extension == 'csv') {
            $PHPExcel = new \PHPExcel_Reader_CSV();
        } elseif ($extension == 'xlsx') {
            $PHPExcel = new \PHPExcel_Reader_Excel2007();
        } else {
            $PHPExcel = new \PHPExcel_Reader_Excel5();
        }

        if (!$PHPExcel->canRead($file)) {
            return [
                'type' => 'fail',
                'msg' => '导入失败，Excel文件错误'
            ];
        }

        $PHPExcelLoad = $PHPExcel->load($file);
        $Sheet = $PHPExcelLoad->getSheet(0);
        $add_list = array();
        /**取得一共有多少行*/
        $allRow = $Sheet->getHighestRow();


        $time = time();
        for ($j = 4; $j <= $allRow; $j++) {
            //中文名
            $name = trim($Sheet->getCellByColumnAndRow(0, $j)->getValue());
            if (!empty($name)) {
                $add_list[$j - 4]['name'] = $name;
                //图片
                $add_list[$j - 4]['img'] = trim($Sheet->getCellByColumnAndRow(1, $j)->getValue());
                //款号
                $add_list[$j - 4]['spu'] = trim($Sheet->getCellByColumnAndRow(2, $j)->getValue());
                //品牌
                $add_list[$j - 4]['brand'] = trim($Sheet->getCellByColumnAndRow(3, $j)->getValue());
                //外箱编号
                $add_list[$j - 4]['box_num'] = trim($Sheet->getCellByColumnAndRow(4, $j)->getValue());
                //颜色中文名
                $add_list[$j - 4]['color_name'] = trim($Sheet->getCellByColumnAndRow(5, $j)->getValue());
                //颜色英文名
                $add_list[$j - 4]['color_name_en'] = trim($Sheet->getCellByColumnAndRow(6, $j)->getValue());
                //尺码
                //XXS
                $add_list[$j - 4]['XXS'] = $Sheet->getCellByColumnAndRow(7, $j)->getValue() ?? 0;
                //XS
                $add_list[$j - 4]['XS'] = $Sheet->getCellByColumnAndRow(8, $j)->getValue() ?? 0;
                //S
                $add_list[$j - 4]['S'] = $Sheet->getCellByColumnAndRow(9, $j)->getValue() ?? 0;
                //M
                $add_list[$j - 4]['M'] = $Sheet->getCellByColumnAndRow(10, $j)->getValue() ?? 0;
                //L
                $add_list[$j - 4]['L'] = $Sheet->getCellByColumnAndRow(11, $j)->getValue() ?? 0;
                //XL
                $add_list[$j - 4]['XL'] = $Sheet->getCellByColumnAndRow(12, $j)->getValue() ?? 0;
                //2XL
                $add_list[$j - 4]['2XL'] = $Sheet->getCellByColumnAndRow(13, $j)->getValue() ?? 0;
                //3XL
                $add_list[$j - 4]['3XL'] = $Sheet->getCellByColumnAndRow(14, $j)->getValue() ?? 0;
                //4XL
                $add_list[$j - 4]['4XL'] = $Sheet->getCellByColumnAndRow(15, $j)->getValue() ?? 0;
                //5XL
                $add_list[$j - 4]['5XL'] = $Sheet->getCellByColumnAndRow(16, $j)->getValue() ?? 0;
                //6XL
                $add_list[$j - 4]['6XL'] = $Sheet->getCellByColumnAndRow(17, $j)->getValue() ?? 0;
                //7XL
                $add_list[$j - 4]['7XL'] = $Sheet->getCellByColumnAndRow(18, $j)->getValue() ?? 0;
                //8XL
                $add_list[$j - 4]['8XL'] = $Sheet->getCellByColumnAndRow(19, $j)->getValue() ?? 0;
                // //出货数量
                // $add_list[$j - 4]['out_num'] = trim($Sheet->getCellByColumnAndRow(20, $j)->getValue());
                //订单总数
                $add_list[$j - 4]['order'] = trim($Sheet->getCellByColumnAndRow(21, $j)->getValue());
                //备注
                $content = trim($Sheet->getCellByColumnAndRow(23, $j)->getValue());
                // $add_list[$j - 4]['supply_time'] = $supply_time;
            }
        }


        foreach ($add_list as $value) {
            # code...
            //amazon_supply_chain
            $res = Db::table('amazon_supply_chain')->where($value)->first();
            if (!$res) {
                $value['out_num'] = $value['XXS'] + $value['XS'] + $value['S'] + $value['M'] + $value['L'] + $value['XL'] + $value['2XL'] + $value['3XL'] + $value['4XL'] + $value['5XL'] + $value['6XL'] + $value['7XL'] + $value['8XL'];
                //插入生成下单表amazon_place_order
                $query['spu'] = $value['spu'];
                $query['color_name'] = $value['color_name'];
                $query['color_name_en'] = $value['color_name_en'];
                $placeres = Db::table('amazon_place_order')->where($query)->first();
                if (!$placeres) {
                    return ['type' => 'fail', 'msg' => '导入失败,无此生产订单' . $query['spu'] . $query['color_name_en']];
                }
                $order = $placeres->order ?? 0;
                if (!$placeres || $order != $value['order']) {
                    return ['type' => 'fail', 'msg' => '导入失败,不存在此下单数据，或订单数有误'];
                }
                $id = $placeres->id;                    //出货总数
                $out_num = $placeres->out_num ?? 0;

                $insert['out_num'] = $value['out_num'] + $out_num;
                //出货时间
                $insert['out_time'] = $time;
                $update = Db::table('amazon_place_order')->where('id', $id)->update($insert);
                if (!$update) {
                    return ['type' => 'fail', 'msg' => '导入失败,插入生产下单数据出错'];
                }
                $valie['out_time'] = $time;
                $value['create_time'] = $time;
                $value['content'] = $content;
                $value['create_user'] = $user_id;

                $insert = Db::table('amazon_supply_chain')->insert($value);
                if (!$insert) {
                    return ['type' => 'fail', 'msg' => '导入失败'];
                }

            }

        }

        return ['type' => 'success', 'msg' => '导入成功'];
    }


    //生成下单列表
    public function PlaceOrderList($params)
    {

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page = $pagenum - 1;
        if ($page != 0) {
            $page = $page * $limit;
        }

        $posttype = $params['posttype'] ?? 1;

        $where['status'] = 1;
        if (isset($params['product_user_id'])) {
            $where['product_user_id'] = $params['product_user_id'];
        }
        if (isset($params['operate_user_id'])) {
            $where['operate_user_id'] = $params['operate_user_id'];
        }
        if (isset($params['supply_user_id'])) {
            $where['supply_user_id'] = $params['supply_user_id'];
        }

        if (isset($params['brand'])) {
            $where['brand'] = $params['brand'];
        }

        if (isset($params['color_name_en'])) {
            $where['color_name_en'] = $params['color_name_en'];
        }
        if (isset($params['name_en'])) {
            $where['name_en'] = $params['name_en'];
        }
        if (isset($params['is_new'])) {
            $where['is_new'] = $params['is_new'];
        }


        $list = Db::table('amazon_place_order');
        $listcount = Db::table('amazon_place_order');
        if (isset($params['start_time']) && isset($params['end_time'])) {
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']);
            $list = $list->whereBetween('supply_time', [$start_time, $end_time]);
            $listcount = $listcount->whereBetween('supply_time', [$start_time, $end_time]);
        }

        if (isset($params['custom_sku'])) {
            $list = $list->where('custom_sku', 'like', '%' . $params['custom_sku'] . '%');
            $listcount = $listcount->where('custom_sku', 'like', '%' . $params['custom_sku'] . '%');
        }
        if (isset($params['spu'])) {
            $list = $list->where('spu', 'like', '%' . $params['spu'] . '%');
            $listcount = $listcount->where('spu', 'like', '%' . $params['spu'] . '%');
        }

        if (isset($where)) {
            $list = $list->where($where);
            $listcount = $listcount->where($where);
        }

        $list = $list->offset($page)->limit($limit)->get();
        $totalNum = $listcount->count();

        foreach ($list as $v) {
            //运营负责人
            $v->operate_user = '';
            $operate_users = $this->GetUsers($v->operate_user_id);
            if ($operate_users) {
                $v->operate_user = $operate_users['account'];
            }
            //产品负责人
            $v->product_user = '';
            $product_users = $this->GetUsers($v->product_user_id);
            if ($product_users) {
                $v->product_user = $product_users['account'];
            }
            //供应链负责人
            $v->supply_user = '';
            $supply_users = $this->GetUsers($v->supply_user_id);
            if ($supply_users) {
                $v->supply_user = $supply_users['account'];
            }
            if ($v->contract_time) {
                $v->contract_time = date('Y-m-d', $v->contract_time);
            }
            if ($v->out_time) {
                $v->out_time = date('Y-m-d', $v->out_time);
            }
            if ($v->supply_time) {
                $v->supply_time = date('Y-m-d', $v->supply_time);
            }

            $v->old_spu = '';
            $spures = Db::table('self_spu')->orwhere('spu', $v->spu)->orwhere('old_spu', $v->spu)->first();

            if ($spures) {
                $v->old_spu = $spures->old_spu ?? '';
            }

            $v->old_custom_sku = '';
            $custom_skures = Db::table('self_custom_sku')->orwhere('custom_sku', $v->custom_sku)->orwhere('old_custom_sku', $v->custom_sku)->first();

            if ($custom_skures) {
                $v->old_custom_sku = $custom_skures->old_custom_sku ?? '';
            }
        }

        if ($posttype == 2) {
            $this->ExcelPlaceOrder($list);
        }

        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }


    //生成下单列表 - 其他
    public function PlaceOrderOtherList($params)
    {
    
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page = $pagenum - 1;
        if ($page != 0) {
            $page = $page * $limit;
        }

        $posttype = $params['posttype'] ?? 1;

        if (isset($params['product_user_id'])) {
            $where['product_user_id'] = $params['product_user_id'];
        }
        if (isset($params['operate_user_id'])) {
            $where['operate_user_id'] = $params['operate_user_id'];
        }
        if (isset($params['supply_user_id'])) {
            $where['supply_user_id'] = $params['supply_user_id'];
        }

        if (isset($params['brand'])) {
            $where['brand'] = $params['brand'];
        }

        if (isset($params['color_name_en'])) {
            $where['color_name_en'] = $params['color_name_en'];
        }
        if (isset($params['name_en'])) {
            $where['name_en'] = $params['name_en'];
        }
        if (isset($params['is_new'])) {
            $where['is_new'] = $params['is_new'];
        }


        $list = Db::table('amazon_place_order_other');
        if (isset($params['start_time']) && isset($params['end_time'])) {
            $start_time = strtotime($params['start_time']);
            $end_time = strtotime($params['end_time']);
            $list = $list->whereBetween('supply_time', [$start_time, $end_time]);
        }

        if (isset($params['spu'])) {
            $list = $list->where('spu', 'like', '%' . $params['spu'] . '%');
        }

        if (isset($where)) {
            $list = $list->where($where);
        }

        $totalNum = $list ->count();
        $list = $list->offset($page)->limit($limit)->get();
        

        foreach ($list as $v) {
            //运营负责人
            $v->operate_user = '';
            $operate_users = $this->GetUsers($v->operate_user_id);
            if ($operate_users) {
                $v->operate_user = $operate_users['account'];
            }
            //产品负责人
            $v->product_user = '';
            $product_users = $this->GetUsers($v->product_user_id);
            if ($product_users) {
                $v->product_user = $product_users['account'];
            }
            //供应链负责人
            $v->supply_user = '';
            $supply_users = $this->GetUsers($v->supply_user_id);
            if ($supply_users) {
                $v->supply_user = $supply_users['account'];
            }

            //创建日期
            if ($v->create_time) {
                $v->create_time = date('Y-m-d', $v->create_time);
            }

            //合同日期
            if ($v->contract_time) {
                $v->contract_time = date('Y-m-d', $v->contract_time);
            }

            //下单日期
            if ($v->supply_time) {
                $v->supply_time = date('Y-m-d', $v->supply_time);
            }

            $v->old_spu = '';
            $spures = Db::table('self_spu')->orwhere('spu', $v->spu)->orwhere('old_spu', $v->spu)->first();

            if ($spures) {
                $v->old_spu = $spures->old_spu ?? '';
            }
        }

        if ($posttype == 2) {
            $this->ExcelPlaceOrderOther($list);
        }

        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
    }
    
    


    //生成下单修改
    public function PlaceOrderEdit($params)
    {
        $id = $params['id'];
        if (isset($params['img'])) {
            $update['img'] = $params['img'];
        }
        if (isset($params['name_en'])) {
            $update['name_en'] = $params['name_en'];
        }
        if (isset($params['price'])) {
            $update['price'] = $params['price'];
        }
        if (isset($params['is_new'])) {
            $update['is_new'] = $params['is_new'];
        }
        if (isset($params['spu'])) {
            $update['spu'] = $params['spu'];
        }
        if (isset($params['custom_sku'])) {
            $update['custom_sku'] = $params['custom_sku'];
        }
        if (isset($params['brand'])) {
            $update['brand'] = $params['brand'];
        }
        if (isset($params['color_name'])) {
            $update['color_name'] = $params['color_name'];
        }
        if (isset($params['color_identifying'])) {
            $update['color_identifying'] = $params['color_identifying'];
        }
        if (isset($params['color_name_en'])) {
            $update['color_name_en'] = $params['color_name_en'];
        }
        if (isset($params['XXS'])) {
            $update['XXS'] = $params['XXS'];
        }
        if (isset($params['XS'])) {
            $update['XS'] = $params['XS'];
        }
        if (isset($params['S'])) {
            $update['S'] = $params['S'];
        }
        if (isset($params['M'])) {
            $update['M'] = $params['M'];
        }
        if (isset($params['L'])) {
            $update['L'] = $params['L'];
        }
        if (isset($params['XL'])) {
            $update['XL'] = $params['XL'];
        }
        if (isset($params['2XL'])) {
            $update['2XL'] = $params['2XL'];
        }
        if (isset($params['3XL'])) {
            $update['3XL'] = $params['3XL'];
        }
        if (isset($params['4XL'])) {
            $update['4XL'] = $params['4XL'];
        }
        if (isset($params['5XL'])) {
            $update['5XL'] = $params['5XL'];
        }
        if (isset($params['6XL'])) {
            $update['6XL'] = $params['6XL'];
        }
        if (isset($params['7XL'])) {
            $update['7XL'] = $params['7XL'];
        }
        if (isset($params['8XL'])) {
            $update['8XL'] = $params['8XL'];
        }
        if (isset($params['out_num'])) {
            $update['out_num'] = $params['out_num'];
        }
        if (isset($params['order'])) {
            $update['order'] = $params['order'];
        }
        if (isset($params['supply_time'])) {
            $update['supply_time'] = strtotime($params['supply_time']);
        }
        if (isset($params['product_user_id'])) {
            $update['product_user_id'] = $params['product_user_id'];
        }
        if (isset($params['operate_user_id'])) {
            $update['operate_user_id'] = $params['operate_user_id'];
        }
        if (isset($params['supply_user_id'])) {
            $update['supply_user_id'] = $params['supply_user_id'];
        }
        if (isset($params['contract_time'])) {
            $update['contract_time'] = strtotime($params['contract_time']);
        }
        if (isset($params['out_time'])) {
            $update['out_time'] = $params['out_time'];
        }

        $res = Db::table('amazon_place_order')->where('id', $id)->update($update);
        if (!$res) {
            return ['type' => 'fail', 'msg' => '修改失败'];
        }
        return ['type' => 'success', 'msg' => '修改成功'];
    }


    //生成下单修改 - 其他
    public function PlaceOrderOtherEdit($params)
    {
        $id = $params['id'];
        if (isset($params['img'])) {
            $update['img'] = $params['img'];
        }
        if (isset($params['name_en'])) {
            $update['name_en'] = $params['name_en'];
        }
        if (isset($params['is_new'])) {
            $update['is_new'] = $params['is_new'];
        }
        if (isset($params['spu'])) {
            $update['spu'] = $params['spu'];
        }

        if (isset($params['brand'])) {
            $update['brand'] = $params['brand'];
        }
        if (isset($params['color_name'])) {
            $update['color_name'] = $params['color_name'];
        }
        if (isset($params['color_identifying'])) {
            $update['color_identifying'] = $params['color_identifying'];
        }
        if (isset($params['color_name_en'])) {
            $update['color_name_en'] = $params['color_name_en'];
        }
        if (isset($params['out_num'])) {
            $update['out_num'] = $params['out_num'];
        }
        if (isset($params['order'])) {
            $update['order'] = $params['order'];
        }
        if (isset($params['supply_time'])) {
            $update['supply_time'] = strtotime($params['supply_time']);
        }
        if (isset($params['product_user_id'])) {
            $update['product_user_id'] = $params['product_user_id'];
        }
        if (isset($params['operate_user_id'])) {
            $update['operate_user_id'] = $params['operate_user_id'];
        }
        if (isset($params['supply_user_id'])) {
            $update['supply_user_id'] = $params['supply_user_id'];
        }
        if (isset($params['contract_time'])) {
            $update['contract_time'] = strtotime($params['contract_time']);
        }
        if (isset($params['style'])) {
            $update['style'] = $params['style'];
        }

        $res = Db::table('amazon_place_order_other')->where('id', $id)->update($update);
        if (!$res) {
            return ['type' => 'fail', 'msg' => '修改失败'];
        }
        return ['type' => 'success', 'msg' => '修改成功'];
    }

    //生成下单删除
    public function PlaceOrderDel($params)
    {
        $id = $params['id'];

        Db::table('amazon_place_order')->where('id', $id)->delete();

        return ['type' => 'success', 'msg' => '删除成功'];
    }

    //生成下单删除 - 其他
    public function PlaceOrderOtherDel($params)
    {
        $id = $params['id'];

        Db::table('amazon_place_order_other')->where('id', $id)->delete();

        return ['type' => 'success', 'msg' => '删除成功'];
    }



    public function UploadImg($params)
    {

        $file = $params['file'];
        $time = time();
        $filename = $file->getClientOriginalName();
        $filename = "d" . $time . "_" . $filename;
        //获取文件后缀名
        $extension = $file->getClientOriginalExtension();
        $rule = ['jpg', 'png', 'gif'];
        if (!in_array($extension, $rule)) {
            return ['type' => 'fail', 'msg' => '图片格式为jpg,png,gif'];
        }
        if (file_exists("/var/www/test/xin/public/admin/img/" . $filename)) {
            return ['type' => 'fail', 'msg' => '文件已存在'];
        } else {
            move_uploaded_file($file, "/var/www/test/xin/public/admin/img/" . $filename);
            $path = "/var/www/test/xin/public/admin/img/" . $filename;
        }
        $data['file_path'] = $path;
        $data['file_name'] = $filename;

        return ['type' => 'success', 'msg' => "http://116.62.169.253:9080/admin/img/".$filename];
    }


    //根据颜色英文名生成标识
    public function GetIdentifying($word)
    {
        //规则，一个单词取前三位字母，全部大写，2个单词取第一个一位，第二个两位    3个单词取3个首位  重复则最后一位往后取   全部重复则最后一位随机
        $word = str_replace("'", "", $word);
        $res = explode(' ', $word);
        $num = count($res);
        if ($num < 0) {
            return '';
        }
        switch ($num) {
            case 1:
                # 单个单词
                //取前三位
                $word = $res[0];
                $word = str_split($word);
                $a = $word[0];
                $b = $word[1];

                $i = 1;
                do {
                    $i++;
                    $c = $word[$i];
                    $words = $a . $b . $c;
                    $res = Db::table('self_color_size')->where('identifying', $words)->first();
                } while ($res);
                break;
            case 2:
                # 两个单词
                $word_a = $res[0];
                $word_b = $res[1];
                $word_a = str_split($word_a);
                $word_b = str_split($word_b);
                $a = $word_a[0];
                $b = $word_b[0];
                $i = 0;
                do {
                    $i++;
                    $c = $word_b[$i];
                    $words = $a . $b . $c;
                    $res = Db::table('self_color_size')->where('identifying', $words)->first();
                } while ($res);
                break;
            case 3:
                # 三个单词
                $word_a = $res[0];
                $word_b = $res[1];
                $word_c = $res[2];
                $word_a = str_split($word_a);
                $word_b = str_split($word_b);
                $word_c = str_split($word_c);
                $a = $word_a[0];
                $b = $word_b[0];
                $i = -1;
                do {
                    $i++;
                    $c = $word_c[$i];
                    $words = $a . $b . $c;
                    $res = Db::table('self_color_size')->where('identifying', $words)->first();
                } while ($res);
                break;
            default:
                # 三个单词
                $word_a = $res[0];
                $word_b = $res[1];
                $word_c = $res[2];
                $word_a = str_split($word_a);
                $word_b = str_split($word_b);
                $word_c = str_split($word_c);
                $a = $word_a[0];
                $b = $word_b[0];
                $i = -1;
                do {
                    $i++;
                    $c = $word_c[$i];
                    $words = $a . $b . $c;
                    $res = Db::table('self_color_size')->where('identifying', $words)->first();
                } while ($res);
                break;
        }
        return strtoupper($words);
    }

    //亚马逊活动任务
    public function ActivityTask($params)
    {

        //分页
        $limit = "";
        if ((!empty($params['page'])) and (!empty($params['limit']))) {
            $limit = " limit " . ($params['page'] - 1) * $params['limit'] . ",{$params['limit']}";
        }
        $where = '1=1';
        $subWhere = '1=1';
        if (!empty($params['store_id'])) {
            $where .= " and s.Id={$params['store_id']}";
        }
        if (!empty($params['father_asin'])) {
            $subWhere .= " and a.father_asin = '{$params['father_asin']}'";
        }
        if (!empty($params['user_id'])) {
            $subWhere .= " and u.Id = {$params['user_id']}";
        }
        if (!empty($params['type_data'])) {
            $subWhere .= " and ac.product_typename in ( '".implode($params['type_data'],"','")."' )";
        }

        echo $params['create_time'][0];

        $sql = "select SQL_CALC_FOUND_ROWS  t.Id,t.ext,t.shop_id,s.store_user,s.shop_name
                    from tasks t
                    left join shop s on s.Id=t.shop_id
                    left join tasks_examine te on te.task_id=t.Id
                    where $where and t.class_id=16 and  te.state=3 group by t.Id
                    {$limit}";
        $task = json_decode(json_encode(Db::select($sql)), true);

        //// 总条数
        if (isset($params['page']) and isset($params['limit'])) {
            $total = db::select("SELECT FOUND_ROWS() as total");
            $return['total'] = $total[0]->total;
        }

        foreach ($task as $key => $value) {
            $ext = json_decode($value['ext'], true);

            // if (!empty($params['create_time']) && isset($params['create_time'][0]) && $params['create_time'][1]) {
            //     if (strtotime($ext['start_time']) != strtotime($params['create_time'][0])  ||
            //          strtotime($ext['end_time']) != strtotime($params['create_time'][1])
            //     ){
            //         unset($task[$key]);
            //         continue;
            //     }
            // }

            if(!empty($params['create_time'][0])&& !empty($params['create_time'][1])){
                 echo $params['create_time'][0];
            }

            if (strtotime($ext['end_time'].' 23:59:59') > time() && strtotime($ext['start_time']) < time()) {
                $task[$key]['active_phase'] = '正在进行';
            } elseif (strtotime($ext['start_time']) > time()) {
                $task[$key]['active_phase'] = '即将退出';
            } elseif (strtotime($ext['end_time'].' 23:59:59') < time()) {
                $task[$key]['active_phase'] = '已结束';
            }


            $asin = $ext['asin'];
            $task[$key]['is_color'] = 0;
            $task[$key]['father_asin'] = $asin;
            if (isset($ext['superposition_coupon'])) {
                if ($ext['superposition_coupon'] == '最多5%，限制每个买家只能兑换一次') {
                    $task[$key]['is_color'] = 1;//浅红色
                }
                if ($ext['superposition_coupon'] == '大额coupon（超过20%）') {
                    $task[$key]['is_color'] = 2;//深红色
                }
            }
            //拼接时间区间
            $task[$key]['time'] = $ext['start_time'] . '-' . $ext['end_time'];

            if ($ext['start_time'] == $ext['end_time']) {
                $task[$key]['days'] = 1;
            } else {
                $task[$key]['days'] = 7;
            }
            $task[$key]['amazon_date'] = $ext['active_time'] ?? '';
            //查询skulist表
//            $skuSql = "select ac.product_typename,a.category_id,a.gender,a.goods_style,a.sales_status,acs.category_status,u.account as user_name
//                            from amazon_skulist a
//                            left join amazon_category ac on ac.id=a.category_id
//                            left join amazon_category_status acs on acs.id=a.sales_status
//                            left join users u on u.Id=a.user_id
//                            where $subWhere and a.father_asin='{$asin}' group by a.father_asin";
            $skuSql = "select ac.product_typename,a.category_id,a.gender,a.goods_style,a.sales_status,u.account as user_name
                            from amazon_link_ranklist a
                            left join amazon_category ac on ac.id=a.category_id
                            left join users u on u.Id=a.user_id
                            where $subWhere and a.father_asin='{$asin}' group by a.father_asin";
            $skuData = json_decode(json_encode(Db::select($skuSql)), true);

            if (!empty($skuData)) {
                $task[$key] = array_merge($task[$key], $skuData[0]);
            //    $tmp .= $asin.',';
            } elseif (!empty($params['father_asin']) || !empty($params['user_id']) || !empty($params['type_data'])) {
                unset($task[$key]);
            }
        }
     //   return dump($tmp);
        $return['total'] = count($task);
        $return['list'] = array_values($task);;
        return $return;
    }

    public function newActivityTaskList($params)
    {
        $task = db::table('tasks as t')
            ->leftJoin('shop as s', 's.Id', '=', 't.shop_id')
            ->leftJoin('tasks_examine as te', 'te.task_id', '=', 't.Id')
            ->where('t.class_id', 16)
            ->where('te.state', 3)
            ->where('t.type', 1);

        // 店铺过滤
        if (!empty($params['store_id'])) {
            $task = $task->where('s.Id', $params['store_id']);
        }
        // fasin过滤
        if (!empty($params['father_asin'])) {
            $asin = '"asin":"'.$params['father_asin'];
            $task = $task->where('t.ext', 'like', '%'.$asin.'%');
        }
        // 任务过滤
        if (!empty($params['task_id'])){
            $task = $task->where('t.Id', $params['task_id']);
        }

        $task = $task->orderBy('t.create_time', 'DESC')
            ->groupBy('t.Id')
            ->get(['t.Id', 't.ext', 't.shop_id', 's.store_user', 's.shop_name']);

        $task = json_decode(json_encode($task), true);

        $list = [];

        if (!empty($params['create_time']) && isset($params['create_time'][0]) && $params['create_time'][1]) {
            $start_time = strtotime($params['create_time'][0]);
            $end_time = strtotime($params['create_time'][1]);
        }

        $activeTime = [];
        foreach ($task as $key => $value) {
            $task[$key]['link_num'] = 1;
            $ext = json_decode($value['ext'], true);
//            // 日期过滤
            //    if (!empty($params['create_time']) && isset($params['create_time'][0]) && $params['create_time'][1]) {
            //         echo $params['create_time'][0];
            //         echo $params['create_time'][1];

            //        if (strtotime($ext['start_time']) != strtotime($params['create_time'][0])  ||
            //            strtotime($ext['end_time']) != strtotime($params['create_time'][1])
            //        ){
            //            unset($task[$key]);
            //            continue;
            //        }
            //    }

            if(isset($start_time)){
                $task_start =  strtotime($ext['start_time']);
                $task_end =  strtotime($ext['end_time']);
                //开始时间大于活动开始时间 或者  结束时间小于活动结束时间
                if($start_time>$task_start||$task_end>$end_time){
                    unset($task[$key]);
                    continue;
                }
            }

            if (strtotime($ext['end_time'].' 23:59:59') > time() && strtotime($ext['start_time']) < time()) {
                $task[$key]['active_phase'] = '正在进行';
            } elseif (strtotime($ext['start_time']) > time()) {
                $task[$key]['active_phase'] = '未开始';
            } elseif (strtotime($ext['end_time'].' 23:59:59') < time()) {
                $task[$key]['active_phase'] = '已结束';
            }

            $asin = $ext['asin'];
            $task[$key]['is_color'] = 0;
            $task[$key]['father_asin'] = $asin;
            if (isset($ext['superposition_coupon'])) {
                if ($ext['superposition_coupon'] == '最多5%，限制每个买家只能兑换一次') {
                    $task[$key]['is_color'] = 1;//浅红色
                }
                if ($ext['superposition_coupon'] == '大额coupon（超过20%）') {
                    $task[$key]['is_color'] = 2;//深红色
                }
            }
            //拼接时间区间
            $task[$key]['time'] = $ext['start_time'] . '-' . $ext['end_time'];

            // 获取日期区间所有日期
            $allDate = [];
            $startTimestamp = strtotime($ext['start_time'] ?? '');
            $endTimestamp = strtotime($ext['end_time'] ?? '');
            if ($startTimestamp > 0 && $endTimestamp > 0){
                do {
                    $allDate[] = date('Y-m-d', $startTimestamp);
                    $startTimestamp+=60*60*24;
                }while($startTimestamp <= $endTimestamp);
            }
            $task[$key]['all_date'] = $allDate;

            if ($ext['start_time'] == $ext['end_time']) {
                $task[$key]['days'] = 1;
            } else {
                $task[$key]['days'] = 7;
            }
            $task[$key]['amazon_date'] = $ext['active_time'] ?? '';
            //查询skulist表
//            $skuSql = "select ac.product_typename,a.category_id,a.gender,a.goods_style,a.sales_status,acs.category_status,u.account as user_name
//                            from amazon_skulist a
//                            left join amazon_category ac on ac.id=a.category_id
//                            left join amazon_category_status acs on acs.id=a.sales_status
//                            left join users u on u.Id=a.user_id
//                            where $subWhere and a.father_asin='{$asin}' group by a.father_asin";
            $skuData = db::table('amazon_fasin as a')
                ->leftJoin('users as u', 'u.Id', '=', 'a.user_id')
                ->where('a.fasin', $asin);
            // if (!empty($params['store_id'])) {
            //     $skuData = $skuData->where('a.shop_id', $params['store_id']);
            // }
            if (!empty($params['user_id'])) {
                $skuData = $skuData->where('u.Id', $params['user_id']);
            }
            if (isset($params['one_cate_id']) && !empty($params['one_cate_id'])){
                $skuData = $skuData->whereIn('a.one_cate_id', $params['one_cate_id']);
            }
            if (isset($params['two_cate_id']) && !empty($params['two_cate_id'])){
                $skuData = $skuData->whereIn('a.two_cate_id', $params['two_cate_id']);
            }
            if (isset($params['three_cate_id']) && !empty($params['three_cate_id'])){
                $skuData = $skuData->whereIn('a.three_cate_id', $params['three_cate_id']);
            }
            $skuData = $skuData->select('u.account','a.*')->first();

            $skuData = json_decode(json_encode($skuData), true);
            //大类
            $task[$key]['one_cate_name'] = '';
            //二类
            $task[$key]['two_cate_name'] = '';
            //三类
            $task[$key]['three_cate_name'] = '';
            //三类
            $task[$key]['account'] = '';
            if (!empty($skuData)) {
                $one_cate = $this->GetCategory($skuData['one_cate_id']);
                if($one_cate){
                    $task[$key]['one_cate_name'] = $one_cate['name'];
                }
                $two_cate = $this->GetCategory($skuData['two_cate_id']);
                if($two_cate){
                    $task[$key]['two_cate_name'] = $two_cate['name'];
                }
                $three_cate = $this->GetCategory($skuData['three_cate_id']);
                if($three_cate){
                    $task[$key]['three_cate_name'] = $three_cate['name'];
                }
                $task[$key] = array_merge($task[$key], $skuData);
                //    $tmp .= $asin.',';
            } elseif (!empty($params['father_asin']) || !empty($params['user_id']) || !empty($params['one_cate_id']) || !empty($params['two_cate_id']) || !empty($params['three_cate_id'])) {
                unset($task[$key]);
                continue;
//                $task[$key]['one_cate_name'] = '';
//                $task[$key]['two_cate_name'] = '';
//                $task[$key]['three_cate_name'] = '';
//                $task[$key]['account']='';
            }

            $shop = $this->GetShop($task[$key]['shop_id'])['shop_name'] ?? '';
            $task[$key]['shop_name'] = $shop;
            $kk = $asin.$task[$key]['shop_id'];
            if (array_key_exists($kk, $list)){

                $list[$kk]['all_date'] = array_merge($list[$kk]['all_date'], $allDate);
                $list[$kk]['link_num'] += 1;
            }else{
                if (!empty($task[$key] ?? [])){
                    $list[$kk] = $task[$key];
                }
            }
        }
        $list = array_values($list);
        $totalNum = count($list);
        // 数组分页
        if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])){
            $offset = $params['limit'] * ($params['page'] - 1);
            $list = array_slice($list, $offset, $params['limit']);
        }else{
            $list = array_slice($list, 0, 30); // 默认第一页，显示30条
        }
        //   return dump($tmp);
        $return['total'] = $totalNum;
        $return['list'] = $list;

        return $return;
    }

    //excel导出 -生产下单
    public function ExcelPlaceOrder($params)
    {
        $data = json_decode(json_encode($params), true);
        $obj = new \PHPExcel();


        $fileName = "生产下单列表" . date('Y-m-d');
        $fileType = 'xlsx';

        // 以下内容是excel文件的信息描述信息
        $obj->getProperties()->setTitle('生产下单列表'); //设置标题

        // 设置当前sheet
        $obj->setActiveSheetIndex(0);

        // 设置当前sheet的名称
        $obj->getActiveSheet()->setTitle('生产下单列表');

        // 列标
        $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA'];

        // 填充第一行数据
        $obj->getActiveSheet()
            ->setCellValue($list[0] . '3', '新品')
            ->setCellValue($list[1] . '3', 'spu')
            ->setCellValue($list[2] . '3', '产品负责人')
            ->setCellValue($list[3] . '3', '运营负责人')
            ->setCellValue($list[4] . '3', '供应链负责人')
            ->setCellValue($list[5] . '3', '下单时间')
            ->setCellValue($list[6] . '3', '英文品名描述')
            ->setCellValue($list[7] . '3', '中文颜色')
            ->setCellValue($list[8] . '3', '英文颜色')
            ->setCellValue($list[9] . '3', '品牌')
            ->setCellValue($list[10] . '3', '工厂合同交期')
            ->setCellValue($list[11] . '3', 'XXS')
            ->setCellValue($list[12] . '3', 'XS')
            ->setCellValue($list[13] . '3', 'S')
            ->setCellValue($list[14] . '3', 'M')
            ->setCellValue($list[15] . '3', 'L')
            ->setCellValue($list[16] . '3', 'XL')
            ->setCellValue($list[17] . '3', '2XL')
            ->setCellValue($list[18] . '3', '3XL')
            ->setCellValue($list[19] . '3', '4XL')
            ->setCellValue($list[20] . '3', '5XL')
            ->setCellValue($list[21] . '3', '6XL')
            ->setCellValue($list[22] . '3', '7XL')
            ->setCellValue($list[23] . '3', '8XL')
            ->setCellValue($list[24] . '3', '下单数量')
            ->setCellValue($list[25] . '3', '已出货数量')
            ->setCellValue($list[26] . '3', '单价');


        // 填充第n(n>=2, n∈N*)行数据
        $length = count($data);
        for ($i = 0; $i < $length; $i++) {
            if ($data[$i]['is_new'] == 1) {
                $is_new = '新品';
            } else {
                $is_new = '老品';
            }
            $obj->getActiveSheet()->setCellValue($list[0] . ($i + 4), $is_new, \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[1] . ($i + 4), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[2] . ($i + 4), $data[$i]['product_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[3] . ($i + 4), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[4] . ($i + 4), $data[$i]['supply_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[5] . ($i + 4), $data[$i]['supply_time'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[6] . ($i + 4), $data[$i]['name_en'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[7] . ($i + 4), $data[$i]['color_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[8] . ($i + 4), $data[$i]['color_name_en'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[9] . ($i + 4), $data[$i]['brand'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[10] . ($i + 4), $data[$i]['contract_time'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[11] . ($i + 4), $data[$i]['XXS'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[12] . ($i + 4), $data[$i]['XS'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[13] . ($i + 4), $data[$i]['S'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[14] . ($i + 4), $data[$i]['M'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[15] . ($i + 4), $data[$i]['L'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[16] . ($i + 4), $data[$i]['XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[17] . ($i + 4), $data[$i]['2XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[18] . ($i + 4), $data[$i]['3XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[19] . ($i + 4), $data[$i]['4XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[20] . ($i + 4), $data[$i]['5XL'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
            $obj->getActiveSheet()->setCellValue($list[21] . ($i + 4), $data[$i]['6XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[22] . ($i + 4), $data[$i]['7XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[23] . ($i + 4), $data[$i]['8XL'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[24] . ($i + 4), $data[$i]['order'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[25] . ($i + 4), $data[$i]['out_num'], \PHPExcel_Cell_DataType::TYPE_STRING);
            $obj->getActiveSheet()->setCellValue($list[26] . ($i + 4), $data[$i]['price'], \PHPExcel_Cell_DataType::TYPE_STRING);
        }

        // 设置加粗和左对齐
        foreach ($list as $col) {
            // 设置第一行加粗
            $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
            // 设置第1-n行，左对齐
            for ($i = 1; $i <= $length + 1; $i++) {
                $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            }
        }

        // 设置列宽
        $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('K')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('M')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('N')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('O')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('P')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('Q')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('R')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('S')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('T')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('U')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('V')->setWidth(30);
        $obj->getActiveSheet()->getColumnDimension('W')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('X')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('Y')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('Z')->setWidth(20);
        $obj->getActiveSheet()->getColumnDimension('AA')->setWidth(20);


        // 导出
        ob_clean();
        if ($fileType == 'xls') {
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
            header('Cache-Control: max-age=1');
            $objWriter = new \PHPExcel_Writer_Excel5($obj);
            $objWriter->save('php://output');
            exit;
        } elseif ($fileType == 'xlsx') {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            exit;
        }
    }


     //excel导出 -生产下单
     public function ExcelPlaceOrderOther($params)
     {
         $data = json_decode(json_encode($params), true);
         $obj = new \PHPExcel();
 
 
         $fileName = "生产下单列表-其他" . date('Y-m-d');
         $fileType = 'xlsx';
 
         // 以下内容是excel文件的信息描述信息
         $obj->getProperties()->setTitle('生产下单列表-其他'); //设置标题
 
         // 设置当前sheet
         $obj->setActiveSheetIndex(0);
 
         // 设置当前sheet的名称
         $obj->getActiveSheet()->setTitle('生产下单列表-其他');
 
         // 列标
         $list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'];
 
         // 填充第一行数据
         $obj->getActiveSheet()
             ->setCellValue($list[0] . '1', '新品')
             ->setCellValue($list[1] . '1', 'spu')
             ->setCellValue($list[2] . '1', '产品负责人')
             ->setCellValue($list[3] . '1', '运营负责人')
             ->setCellValue($list[4] . '1', '供应链负责人')
             ->setCellValue($list[5] . '1', '下单时间')
             ->setCellValue($list[6] . '1', '英文品名描述')
             ->setCellValue($list[7] . '1', '中文颜色')
             ->setCellValue($list[8] . '1', '英文颜色')
             ->setCellValue($list[9] . '1', '品牌')
             ->setCellValue($list[10] . '1', '工厂合同交期')
             ->setCellValue($list[11] . '1', '款式')
             ->setCellValue($list[12] . '1', '下单数量')
             ->setCellValue($list[13] . '1', '已出货数量');
 
 
         // 填充第n(n>=2, n∈N*)行数据
         $length = count($data);
         for ($i = 0; $i < $length; $i++) {
             if ($data[$i]['is_new'] == 1) {
                 $is_new = '新品';
             } else {
                 $is_new = '老品';
             }
             $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $is_new, \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
             $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $data[$i]['spu'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $data[$i]['product_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[3] . ($i + 2), $data[$i]['operate_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[4] . ($i + 2), $data[$i]['supply_user'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[5] . ($i + 2), $data[$i]['supply_time'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[6] . ($i + 2), $data[$i]['name_en'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[7] . ($i + 2), $data[$i]['color_name'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[8] . ($i + 2), $data[$i]['color_name_en'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[9] . ($i + 2), $data[$i]['brand'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[10] . ($i + 2), $data[$i]['contract_time'], \PHPExcel_Cell_DataType::TYPE_STRING);//将其设置为文本格式
             $obj->getActiveSheet()->setCellValue($list[11] . ($i + 2), $data[$i]['style'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[12] . ($i + 2), $data[$i]['order'], \PHPExcel_Cell_DataType::TYPE_STRING);
             $obj->getActiveSheet()->setCellValue($list[13] . ($i + 2), $data[$i]['out_num'], \PHPExcel_Cell_DataType::TYPE_STRING);
         }
 
         // 设置加粗和左对齐
         foreach ($list as $col) {
             // 设置第一行加粗
             $obj->getActiveSheet()->getStyle($col . '1')->getFont()->setBold(true);
             // 设置第1-n行，左对齐
             for ($i = 1; $i <= $length + 1; $i++) {
                 $obj->getActiveSheet()->getStyle($col . $i)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
             }
         }
 
         // 设置列宽
         $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('B')->setWidth(30);
         $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('D')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('F')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('G')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('H')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('I')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('J')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('K')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('L')->setWidth(30);
         $obj->getActiveSheet()->getColumnDimension('M')->setWidth(20);
         $obj->getActiveSheet()->getColumnDimension('N')->setWidth(20);
 
 
         // 导出
         ob_clean();
         if ($fileType == 'xls') {
             header('Content-Type: application/vnd.ms-excel');
             header('Content-Disposition: attachment;filename="' . $fileName . '.xls');
             header('Cache-Control: max-age=1');
             $objWriter = new \PHPExcel_Writer_Excel5($obj);
             $objWriter->save('php://output');
             exit;
         } elseif ($fileType == 'xlsx') {
             header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
             header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
             header('Cache-Control: max-age=1');
             $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
             $objWriter->save('php://output');
             exit;
         }
     }



     public function BuhuoRequestList($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;

        $page = $pagenum - 1;
        if ($page != 0) {
            $page = $page * $limit;
        }

         $list = DB::table('amazon_buhuo_request as ar')
             ->leftjoin('amazon_buhuo_detail as ad','ar.id','=','ad.request_id')
             ->leftjoin('self_sku as a','a.id','=','ad.sku_id')
             ->leftjoin('self_custom_sku as b','b.id','=','a.custom_sku_id')
             ->leftjoin('self_spu as c','c.id','=','b.spu_id')
             ->where('ar.request_status','>',2);

         if(!empty($params['shop_id'])){
            $list = $list->where('ar.shop_id',$params['shop_id']);
         }
         if(!empty($params['sku'])){
             $skuId = $this->GetSkuId($params['sku']);
             $list = $list->where('a.sku_id',$skuId);
         }
         if(!empty($params['custom_sku'])){
             $customSkuId = $this->GetCustomSkuId($params['custom_sku']);
             $list = $list->where('b.custom_sku_id',$customSkuId);
         }
         if(!empty($params['spu'])){
             $spuId = $this->GetSpuId($params['spu']);
             $list = $list->where('c.spu_id',$spuId);
         }
         if(!empty($params['user_id'])){
             $list = $list->where('ar.request_userid',$params['user_id']);
         }
         if(!empty($params['start_time'])){
             $list = $list->where('ar.request_time','>',$params['start_time']);
         }
         if(!empty($params['end_time'])){
             $list = $list->where('ar.request_time','<',$params['end_time']);
         }

         $totalNum = $list->count();
         $list = $list
            ->offset($page)
            ->limit($limit)
            ->orderby('request_time','desc')
            ->get(['a.sku','a.old_sku','a.id as sku_id','b.id as custom_sku_id','b.custom_sku','b.old_custom_sku','c.id as spu_id','c.spu','c.old_spu','ad.request_num','ad.transportation_mode_name',
                'ad.transportation_type','ad.box_data_detail','ad.request_id','ar.shop_id','ar.request_userid','ar.request_time']);

         foreach ($list as $v){
            $shop = $this->GetShop($v->shop_id);
            if($shop){
                $v->shop_name = $shop['shop_name'];
            }else{
                $v->shop_name = '';
            }
            $user = $this->GetUsers($v->request_userid);
             if($user){
                 $v->user_name = $user['account'];
             }else{
                 $v->user_name = '';
             }
            //  $skudata = $this->GetSku($v->sku);
            //  if($skudata){
            //      $v->sku = $skudata['sku'];
            //      if($skudata['old_sku']){
            //          $v->old_sku = $skudata['old_sku'];
            //      }else{
            //          $v->old_sku = '';
            //      }
            //  }

            //  $customskudata = $this->GetCustomSkus($v->sku);
            //  if($customskudata){
            //      $v->custom_sku = $skudata['custom_sku'];
            //      if($customskudata['old_custom_sku']){
            //          $v->old_custom_sku = $customskudata['old_custom_sku'];
            //      }else{
            //          $v->old_custom_sku = '';
            //      }
            //  }

            //  $spudata = $this->GetSpu($v->spu_id);
            //  if($spudata){
            //      $v->spu = $spudata['spu'];
            //      if($spudata['old_spu']){
            //          $v->old_spu = $spudata['old_spu'];
            //      }else{
            //          $v->old_spu = '';
            //      }
            //  }
            $box_data = json_decode($v->box_data_detail,true);
            if(!empty($box_data)){
                foreach ($box_data as $k=>$b){
                    if($b>0){
                        $box_no = $k+1;
                        $v->box_detail[] = '第'.$box_no.'箱 : '.$b.'件';
                    }
                }
            }else{
                $v->box_detail = [];
            }
         }

        return [
            'data' => $list,
            'totalNum' => $totalNum,
        ];
     }

    //生产下单任务修改
     public function updateOrder($params){
        //根据token获取用户
        $user = DB::table('users')->where('token',$params['token'])->select('Id')->first();
         if(!$params['sales_market']||!$params['sale_crowd']||!$params['supply_user']||!$params['id']||!$params['expect_date']||!$params['tag']||!$params['shop_id']||!$params['is_optimization']){
             return false;
         }
         //销售市场1.美国 2.欧洲 3.日本
         $update['sales_market'] = $params['sales_market'];
         //销售人群1.成年男性 2.成年女性 3.中大童 4.幼童
         $update['sale_crowd'] = $params['sale_crowd'];
         $update['is_optimization'] = $params['is_optimization'];
         $update['tag'] = $params['tag'];
         if(isset($params['spu'])){
             $update['spulist'] = implode(",",$params['spu']);
         }
         //供应链负责人
         $supply_user = '';
         if(isset($params['supply_user'])){
             $order_id = substr(substr(json_encode(array("order_id" => $params['id'])), 1), 0, -1);
             $task = DB::table('tasks')->where('ext','like',"%{$order_id}%")->select('Id')->first();
             if(!empty($task)){
                 $task_son = DB::table('tasks_son')->where('task_id',$task->Id)->where('task','like',"%下单数据录入艾诺科%")->select('user_id','Id')->first();
                 if($task_son->user_id!=$params['supply_user'][0]){
                     $call_data['Id'] = $task_son->Id;
                     $call_data['user_id'] = $params['supply_user'][0];
                     $call_data['task_id'] = $task->Id;
                     $call_task = new \App\Libs\wrapper\Task();
                     $call_task->node_task_update($call_data);
                 }
             }
             $update['supply_user'] = implode(',',$params['supply_user']);
         }

         $update['expect_date'] = json_encode($params['expect_date']);

         //店铺
         $update['shop_id'] = $params['shop_id']??0;
         // 平台
         $platformId = $params['platform_id'] ?? 0;
         if ($update['shop_id'] != 0){
             $shop = db::table('shop')->where('id', $params['shop_id'])->first();
             $platformId = $shop->platform_id ?? 0;
         }
         if (empty($platformId)){
             return [
                 'type' => 'fail',
                 'msg' =>  '未给定平台标识或店铺未绑定平台！'
             ];
         }
         $update['platform_id'] = $platformId;
         $task_id = DB::table('amazon_place_order_task')->where('id',$params['id'])->update($update);
         if(!$task_id){
             return false;
         }

         return 1;
     }

    //生产下单任务详情修改
     public function updateOrderDetail($params){
        try{
            $order_id = $params['order_id'];
            db::beginTransaction();
            foreach ($params['data'] as $v){
                $thisid = intval($v['id']);
                $update = DB::table('amazon_place_order_detail')->where('id',$thisid)->update(['order_num'=>json_encode($v['order_num'])]);
                if(!$update){
                    throw new \Exception('订单详情订单数量修改失败！');
                }
            }
            $detail = DB::table('amazon_place_order_detail')->where('order_id',$order_id)->select('order_num')->get();
            $total_num = 0;
            foreach ($detail as $d){
                $order_num = json_decode($d->order_num,true);
                $order_num = array_sum($order_num);
                $total_num += $order_num;
            }
            $task = DB::table('amazon_place_order_task')->where('id',$order_id)->update(['order_num'=>$total_num]);
//            if(!$task){
//                throw new \Exception('订单数量修改失败！');
//            }
            db::commit();
            return ['code' => 200];
        }catch (\Exception $e){
            db::rollback();
            return ['code' => 500, 'msg' => '修改失败！原因：'.$e->getMessage().'；位置：'.$e->getLine()];
        }
     }

    /**
     * @Desc:更新任务订单详情
     * @param $params
     * @return array|string[]
     * @author: Liu Sinian
     * @Time: 2023/2/22 14:26
     */
    public function updatePlaceOrderDetail($params)
    {
        try {
            // 校验参数
            $placeOrderTaskModel = $this->_checkParams($params);
            // 开启事务
            DB::beginTransaction();

            // 删除任务订单原有
//            DB::connection()->enableQueryLog();
            $placeOrderDetailModel = $this->amazonPlaceOrderDetailModel::query()->where('order_id', $placeOrderTaskModel->id)->delete();
//            var_dump(DB::getQueryLog());exit();
            $skuNum = 0;
            $orderNum = 0;
            $spuList = array();
            // 处理明细
            foreach ($params['custom_sku_list'] as $item){
                $customSku = $item['custom_sku'];
                $customSkuModel = Db::table('self_custom_sku as a')
                    ->leftjoin('self_color_size as b','a.color','=','b.identifying')
                    ->where('a.custom_sku',$customSku)
                    ->orwhere('a.old_custom_sku',$customSku)
                    ->select('a.spu','a.custom_sku','a.color','a.size','b.english_name as color_name_en','b.name as color_name')
                    ->first();
                if(empty($customSkuModel)){
                    throw new \Exception('没有'.$customSku.'的数据');
                }

                // 获取旧spu
                $oldSpu = $this->GetOldSpu($customSkuModel->spu);
                if($oldSpu){
                    $spuList[] = $oldSpu;
                }else{
                    $spuList[] = $customSkuModel->spu;
                }
                $num = json_encode($item['order_num']);
                $detailSave['name_en'] = $item['name_en'];
                $detailSave['spu'] = $customSkuModel->spu;
                $detailSave['custom_sku'] = $customSkuModel->custom_sku;
                $detailSave['size'] = $customSkuModel->size;
                $detailSave['color_name'] = $customSkuModel->color_name;
                $detailSave['color_name_en'] = $customSkuModel->color_name_en;
                $detailSave['order_num'] =  $num;
                $detailSave['order_id'] = $placeOrderTaskModel->id;

                // 保存操作
                // DB::connection()->enableQueryLog();
                $orderDetailId = $this->amazonPlaceOrderDetailModel::query()->insertGetId($detailSave);
                // var_dump(DB::getQueryLog());
                if(empty($orderDetailId)){
                    throw new \Exception('新增下单明细数据失败');
                }

                // 计算订单数量以及sku数量
                $orderNum += array_sum($item['order_num']);
                $skuNum++;
            }
            $spuList = array_unique($spuList);
            $cate = DB::table('self_spu')->where('spu',$spuList[0])->orWhere('old_spu',$spuList[0])->select('one_cate_id','two_cate_id','three_cate_id')->first();
            if(empty($cate)){
                return [
                    'type' => 'fail',
                    'msg' => 'spu错误'
                ];
            }
            //修改计划数据
            $taskSave['sku_count'] = $skuNum;
            $taskSave['order_num'] = $orderNum;
            $taskSave['spulist'] = implode(",",$spuList);
            $taskSave['one_cate_id'] = $cate->one_cate_id;
            $taskSave['two_cate_id'] = $cate->two_cate_id;
            $taskSave['three_cate_id'] = $cate->three_cate_id;
            // 更新任务订单数据  如果数据没有任何改变，则返回值为0
            $taskId = $this->amazonPlaceOrderTaskModel::query()->where('id', $placeOrderTaskModel->id)->update($taskSave);
//            var_dump($taskId);exit();
//            if(empty($taskId)){
//                throw new \Exception('任务订单更新错误！');
//            }

            DB::commit(); // 事务提交

            return ['code' => 200, 'msg' => '保存成功！'];
        }catch (\Exception $e){
            DB::rollback(); // 事务回滚

            return ['code' => 500, 'msg' => '保存失败！错误原因：'.$e->getMessage()];
        }
    }

    /**
     * @Desc:校验任务订单参数
     * @param $params
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object
     * @throws \Exception
     * @author: Liu Sinian
     * @Time: 2023/2/22 14:26
     */
    private function _checkParams($params)
    {
        if (isset($params['order_id']) && !empty($params['order_id'])){
            // 查询任务订单是否存在
            $placeOrderTaskModel = $this->amazonPlaceOrderTaskModel::query()->where('id', $params['order_id'] ?? 0)->first();
            if (empty($placeOrderTaskModel)){
                throw new \Exception('任务订单不存在!');
            }
        }else{
            throw new \Exception('未给定任务订单标识!');
        }
        // 检查任务订单状态
        $updateStatus = [1];
        if (!in_array($placeOrderTaskModel->status, $updateStatus)){
            throw new \Exception('任务订单非待审核状态不予修改!');
        }

        // 校验明细数据
        if (isset($params['custom_sku_list']) && !empty($params['custom_sku_list'])){
            $errcs = [];
            $is_repeats = [];
            // 面料查重
            foreach ($params['custom_sku_list'] as $cs) {
                # code...
                $customSkuId = $this->GetCustomSkuId($cs['custom_sku']);

                if(in_array($customSkuId,$is_repeats)){
                    throw new \Exception('存在重复库存sku数据，请重新检查删除重复数据');
                }else{
                    $is_repeats[] = $customSkuId;
                }
//                $img = $this->GetCustomskuImg($cs['custom_sku']);
//                if($img==''){
//                    $errcs[] = $cs['custom_sku'];
//                }
            }
//            if(count($errcs)>0){
//                $errcsmsg = implode(",", $errcs);
//                throw new \Exception('库存sku:'.$errcsmsg.'无图片，无法下单');
//            }
        }else{
            throw new \Exception('未给定商品信息!');
        }

        return $placeOrderTaskModel;
    }

//    public function spuTime($params){
//
//        $pagenum = isset($params['page']) ? $params['page'] : 1;
//        $limit = isset($params['limit']) ? $params['limit'] : 30;
//        $page  =  $pagenum- 1;
//        if($page!=0){
//            $page  =  $page * $limit;
//        }
//
//        if($params['type']==1){
//            //获取有报价数据得spu作为spu基础信息
//            $spulist = DB::table('self_spu as a')
////                ->leftJoin('anok_enquiries as b','a.id','=','b.spu_id')
//                ->leftJoin('self_base_spu as b','a.base_spu_id','=','b.id');
////                ->leftJOin('cloudhouse_contract as d','a.id','=','d.spu_id');
//            if(!empty($params['spu'])){
//                $selectSpu = $params['spu'];
//                $spulist = $spulist->where(function($query) use($selectSpu){
//                    $query->Where('a.spu','like','%'.$selectSpu.'%')->orWhere('a.old_spu','like','%'.$selectSpu.'%');
//                });
//            }
////            if(!empty($params['input_userid'])){
////                $spulist = $spulist->where('d.create_user',$params['input_userid']);
////            }
//            if(!empty($params['product_user_id'])){
//                $spulist = $spulist->where('b.user_id',$params['product_user_id']);
//            }
//            // 品类过滤
//            if (isset($params['one_cate_id']) && !empty($params['one_cate_id'])){
//                $spulist->whereIn('a.one_cate_id', $params['one_cate_id']);
//            }
//            if (isset($params['two_cate_id']) && !empty($params['two_cate_id'])){
//                $spulist->whereIn('a.two_cate_id', $params['two_cate_id']);
//            }
//            if (isset($params['three_cate_id']) && !empty($params['three_cate_id'])){
//                $spulist->whereIn('a.three_cate_id', $params['three_cate_id']);
//            }
//            $totalNum = $spulist->where('b.is_new',1)->count();
//            $spulist= $spulist->offset($page)
//                ->limit($limit)
//                ->where('b.is_new',1)
//                ->orderBy('b.create_time','desc')
//                ->select('a.spu','a.old_spu','a.id as spu_id', 'a.one_cate_id','a.two_cate_id','a.three_cate_id', 'a.content', 'b.id as base_id','b.user_id')
//                ->get();
//        }
//
//        if($params['type']==2){
//            //获取有下单数据得spu作为spu基础信息
//            $amazonPlaceOrderTaskMdl = $this->amazonPlaceOrderTaskModel::query()
//                ->where('type', 2)
//                ->where('status', '>', 0);
//
//            $amazonPlaceOrderTaskMdl->orderBy('creattime', 'desc');
//            $spulist = [];
//            $spuArray = array();
//            $amazonPlaceOrderTaskMdl = $amazonPlaceOrderTaskMdl->get();
//            foreach ($amazonPlaceOrderTaskMdl as $item){
//                $spuArr = explode(',', $item->spulist);
//                $spuArray = array_merge($spuArr, $spuArray);
//            }
//            // 获取spu信息
//            $spuAndBaseSpuMdl = $this->spuModel::query()
//                ->leftJoin('self_base_spu as sbs', 'sbs.id', '=', 'self_spu.base_spu_id')
//                ->select('self_spu.*', 'sbs.user_id', 'sbs.base_spu', 'sbs.old_base_spu');
//            // 过滤条件
////            // 跟单人
////            if(!empty($params['input_userid'])){
////                $anokContractClothingMdl = $this->anokContractClothingModel::query()
////                    ->where('input_userid',$params['input_userid'])
////                    ->select('goods_no')
////                    ->get();
////                if (!empty($anokContractClothingMdl)){
////                    $spuArr = array_column($anokContractClothingMdl->toArray(), 'goods_no');
////                    $spuAndBaseSpuMdl->where(function ($query) use ($spuArr){
////                        return $query->where('self_spu.spu', 'in', $spuArr)
////                            ->orWhere('self_spu.old_spu', 'in', $spuArr);
////                    });
////                }
////            }
//            // sku
//            if(!empty($params['spu'])){
//                $spuAndBaseSpuMdl->where(function ($query) use ($params){
//                    return $query->where('self_spu.spu', 'like', '%'.$params['spu'].'%')
//                        ->orWhere('self_spu.old_spu', 'like', '%'.$params['spu'].'%');
//                });
//            }
//            // 产品开发员
//            if(!empty($params['product_user_id'])){
//                $spuAndBaseSpuMdl->where('sbs.user_id', $params['product_user_id']);
//            }
//// 品类过滤
//            if (isset($params['one_cate_id']) && !empty($params['one_cate_id'])){
//                $spulist->whereIn('self_spu.one_cate_id', $params['one_cate_id']);
//            }
//            if (isset($params['two_cate_id']) && !empty($params['two_cate_id'])){
//                $spulist->whereIn('self_spu.two_cate_id', $params['two_cate_id']);
//            }
//            if (isset($params['three_cate_id']) && !empty($params['three_cate_id'])){
//                $spulist->whereIn('self_spu.three_cate_id', $params['three_cate_id']);
//            }
//
//            $spuAndBaseSpuMdl = $spuAndBaseSpuMdl->get();
//            foreach ($amazonPlaceOrderTaskMdl as $item){
//                $spuArr = explode(',', $item->spulist);
//                foreach ($spuArr as $spu){
//                    foreach ($spuAndBaseSpuMdl as $spuItem){
//                        if ($spu == $spuItem->spu || $spu == $spuItem->old_spu){
//                            $spulist[] = [
//                                'place_order_task_id' => $item->id,
//                                'user_id' => $item->user_id,
//                                'status' => $item->status,
//                                'status_name' => self::AMAZON_PLACE_ORDER_TASK_STATUS_NAME[$item->status],
//                                'spu' => $spu,
//                                'shop_id' => $item->shop_id,
//                                'created_at' => $item->creattime,
//                                'spu_id' => $spuItem->id ?? 0,
//                                'old_spu' => $spuItem->old_spu ?? '',
//                                'user_id' => $spuItem->user_id ?? 0,
//                                'base_id' => $spuItem->base_spu_id ?? 0,
//                                'one_cate_id' => $spuItem->one_cate_id,
//                                'two_cate_id' => $spuItem->two_cate_id,
//                                'three_cate_id' => $spuItem->three_cate_id,
//                                'content' => $spuItem->content
//                            ];
//                        }
//                    }
//                }
//            }
//            $totalNum = count($spulist);
//            // 数组分页
//            if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])){
//                $offset = $params['limit'] * ($params['page'] - 1);
//                $spulist = array_slice($spulist, $offset, $params['limit']);
//            }else{
//                $spulist = array_slice($spulist, 0, 30); // 默认第一页，显示30条
//            }
//        }
//
//        $spulist = json_decode(json_encode($spulist),true);
//
//        $data = array();
//
//        foreach ($spulist as $k=>$v){
//
//            if($v['old_spu']){
//                $spu = $v['old_spu'];
//            }else{
//                $spu = $v['spu'];
//            }
//            $data[$k]['img'] = $this->GetBaseSpuImg($v['base_id']);
//            $nspu = preg_replace('/([\x80-\xff]*)/i','',$v['spu']);
//            $data[$k]['spu'] = $spu;
//            $data[$k]['enquiries'] = array();  //报价数据
//            $data[$k]['devclothing'] = array();  //打样数据
//            $data[$k]['contract_clothing'] = array();  //下单数据
//            $data[$k]['contract_no'] = ''; //合同号
//            $data[$k]['contract_report_date'] = '';
//            $data[$k]['contract_create_time'] = '';
//            $data[$k]['shipment_time'] = '';
//            $data[$k]['in_house_time'] = '';
//            $data[$k]['out_house_time'] = '';
//            $data[$k]['qc_req_date'] = '';
//            $data[$k]['qc_complete_date'] = '';
//            $data[$k]['contract_submit'] = '';
//            $data[$k]['contract_end'] = '';
//            $data[$k]['order_time'] = '';
////            $newSpu = $this->GetNewSpu($spu);
//
//            $data[$k]['product_user'] = $this->GetUsers($v['user_id'])['account'];
//
//            // 品类
//            //大类
//            $data[$k]['one_cate_name'] = '';
//            $one_cate = $this->GetCategory($v['one_cate_id']);
//            if($one_cate){
//                $data[$k]['one_cate_name'] = $one_cate['name'];
//            }
//
//            //二类
//            $data[$k]['two_cate_name'] = '';
//            $two_cate = $this->GetCategory($v['two_cate_id']);
//            if($two_cate){
//                $data[$k]['two_cate_name'] = $two_cate['name'];
//            }
//
//            //三类
//            $data[$k]['three_cate_name'] = '';
//            $three_cate = $this->GetCategory($v['three_cate_id']);
//            if($three_cate){
//                $data[$k]['three_cate_name'] = $three_cate['name'];
//            }
//            // 品名
//            $data[$k]['content'] = $v['content'] ?? '';
//            // 体系类别
//            // 暂时放空，等后续对接修改
//            $data[$k]['system_category'] = '';
//
//            if($params['type']==1) {
//                //获取报价数据
//                $enquiries = DB::table('anok_enquiries')->where('spu_id', $v['spu_id'])->where('status', 5)->where('type', '已报价')->select('type', 'enquiries_date', 'offer_date')->get();
//                if (!empty($enquiries)) {
//                    $data[$k]['enquiries'] = json_decode(json_encode($enquiries), true);
//                }
//                //获取打样数据
//                $devclothing = DB::table('anok_devclothing')->where('spu', $spu)->where('status', 5)->select('version', 'req_date', 'devclothing_date', 'piban_date', 'req_status')->get();
//                if (!empty($devclothing)) {
//                    $data[$k]['devclothing'] = json_decode(json_encode($devclothing), true);
//                }
//                //获取下单数据
//                $contract_clothing = DB::table('anok_contract_clothing')->where('status',5)->where('goods_no',$spu)->select('submit_date','pass_date','billno','input_userid')->orderBy('input_date','asc')->first();
//                if(!empty($contract_clothing)){
//                    $data[$k]['contract_clothing'] = json_decode(json_encode($contract_clothing),true);
//                }
//            }
//
//            if($params['type']==2){
//                //获取下单数据
//                $contract_clothing = DB::table('anok_contract_clothing')
//                    ->where('plan_id', 'like', '%'.$v['place_order_task_id'].'%')
//                    ->where('status',5)
//                    ->where('goods_no',$spu)
//                    ->select('submit_date','pass_date','billno','input_userid')
//                    ->orderBy('input_date','asc')
//                    ->first();
//                if(!empty($contract_clothing)){
//                    $data[$k]['contract_clothing'] = json_decode(json_encode($contract_clothing),true);
//                    $data[$k]['input_user'] = $this->GetUsers($contract_clothing->input_userid)['account'];
//                }
//
//                // 获取E老板下单数据 取任务下单时间最新的一条数据
//                $data[$k]['e_order_task_created_date'] = $v['created_at'];
//                $data[$k]['e_order_task_id'] = $v['place_order_task_id'];
//                $data[$k]['e_order_task_approved_date'] = '';
//                $taskMdl = $this->taskModel::query()
//                    ->leftJoin('tasks_examine as te', 'te.task_id', '=', 'tasks.Id')
//                    ->where('tasks.type', 1)
//                    ->where('tasks.class_id', 19)
//                    ->where('tasks.ext', 'like', '%order_id='.$v['place_order_task_id'].'%')
//                    ->where('te.state', 3)
//                    ->select('tasks.*', 'te.time_sh')
//                    ->first();
//                if (!empty($taskMdl)){
//                    $data[$k]['e_order_task_approved_date'] = $taskMdl->time_sh;
//                }
//            }
//
//            if(isset($data[$k]['contract_clothing']['billno'])){
//                //获取合同交期数据
//                $contract = DB::table('cloudhouse_contract')->where('exp_contractno',$data[$k]['contract_clothing']['billno'])->where('spu',$nspu)->select('report_date','contract_no','create_time','create_user')->orderBy('create_time','asc')->first();
//                //获取QC质检数据
//                if(!empty($contract)){
//                    $data[$k]['input_user'] = $this->GetUsers($contract->create_user)['account'];
//                    $data[$k]['contract_no'] = $contract->contract_no;
//                    $data[$k]['contract_create_time'] = $contract->create_time;
//                    $data[$k]['contract_report_date'] = $contract->report_date;
//                    //获取合同审批数据
//                    $contract_date = DB::table('cloudhouse_contract_total')->where('contract_no',$contract->contract_no)->select('pursubmit_date','purend_date')->first();
//                    if(!empty($contract_date)){
//                        $data[$k]['contract_submit'] = $contract_date->pursubmit_date;
//                        $data[$k]['contract_end'] = $contract_date->purend_date;
//                    }
//                    $qc = DB::table('anok_qc_trip')->where('goods_no',$nspu)->where('purcontract_no',$contract->contract_no)->select('req_date','complete_date','purcontract_no','idate','itype')->orderBy('req_date','asc')->first();
//                    if(!empty($qc)){
//                        $data[$k]['qc_req_date'] = $qc->req_date;
//                        $data[$k]['qc_complete_date'] = $qc->complete_date;
//                    }
//                    //获取合同出货数据,入库数据
//
//                    $data[$k]['contract_report_date'] = $contract->report_date;
//                    $shipment = DB::table('goods_transfers_detail as a')
//                        ->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')
//                        ->where('a.contract_no',$contract->contract_no)
//                        ->where('a.spu_id',$v['spu_id'])
//                        ->orderBy('a.createtime','asc')
//                        ->select('a.createtime','a.contract_no','a.receive_time','b.yj_arrive_time')
//                        ->first();
//                    if(!empty($shipment)){
//                        $data[$k]['shipment_time'] = $shipment->createtime;
//                        $data[$k]['in_house_time'] = $shipment->receive_time;
//                        $data[$k]['logistics_arrive_time'] = $shipment->yj_arrive_time;
//                    }
////获取出库计划数据
//                    $buhuo = DB::table('amazon_buhuo_request as a')->leftJoin('amazon_buhuo_detail as b','a.id','=','b.request_id')->where('b.spu_id',$v['spu_id'])->where('a.request_status','!=',1)->select('a..request_time','b.id')->orderBy('a..request_time','asc')->first();
//                    if(!empty($buhuo)){
//                        $data[$k]['out_house_rq'] = $buhuo->request_time;
//                        //获取出库时间
//                        $request_id_json = substr(substr(json_encode(array("request_id" => "{$buhuo->id}")), 1), 0, -1);
//                        $out_house = Db::table('tasks')->where('ext', 'like', "%{$request_id_json}%")->where('state','!=',2)->select('Id')->first();
//                        if(!empty($out_house)){
//                            $task_son = Db::table('tasks_son')->where('task_id',$out_house->Id)->where('task','审核数据，确认出库')->select('time_end_sj')->first();
//                            if(!empty($task_son)){
//                                $data[$k]['out_house_time'] = $task_son->time_end_sj;
//                            }
//                        }
//                    }
//                    $order = DB::table('amazon_order_item')->where('spu_id',$v['spu_id'])->select('amazon_time')->orderBy('amazon_time','asc')->first();
//                    if(!empty($order)){
//                        $data[$k]['order_time'] = $order->amazon_time;
//                    }
//                }
//
//            }
//
//
//
//
//        }
//        return [
//            'data' => $data,
//            'totalNum' => $totalNum
//        ];
//
//    }
    public function spuTime($params){
        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        if($params['type']==1){
            //获取有报价数据得spu作为spu基础信息
            $enquiries = $this->anokEnquiriesModel::query()->orderBy('offer_date', 'desc')->get();
            $enquiriesIds = [];
            $data = [];
            foreach ($enquiries as $v){
                if (!isset($data[$v->spu])){
                    $data[$v->spu] = [
                        'offer_date' => $v->offer_date,
                        'id' => $v->id
                    ];
                }else{
                    if ($v->offer_date > $data[$v->spu]['offer_date']){
                        $data[$v->spu] = [
                            'offer_date' => $v->offer_date,
                            'id' => $v->id
                        ];
                    }
                }
            }
            $enquiriesIds = array_column($data, 'id');
            // 只显示有报价的数据
            $enquiriesModel = $this->anokEnquiriesModel::query()
                ->whereIn('id', $enquiriesIds)
                ->where('status', 5);
//                ->where('enquiries_date', '>=', '2023-02-27 00:00:00');
            // 过滤时间段
            if (isset($params['offer_date']) && !empty($params['offer_date'])){
                $enquiriesModel->whereBetween('offer_date', $params['offer_date']);
            }
            // 过滤报价类型
            if (isset($params['quote_type']) && !empty($params['quote_type'])){
                $enquiriesModel->where('type', $params['quote_type']);
            }
            // 跟单员过滤
            if(isset($params['maker_id']) && !empty($params['maker_id'])){
                $anokContractClothingMdl = $this->anokContractClothingModel::query()
                    ->where('maker_id', $params['maker_id'])
                    ->select('goods_no')
                    ->get();
                $spu = [];
                if ($anokContractClothingMdl->isNotEmpty()){
                    $spu = array_column($anokContractClothingMdl->toArray(), 'goods_no');
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 过滤初样
            if (isset($params['initial_sample'])){
                $spu = [];
                if($params['initial_sample']){
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 1)
                        ->where('devclothing_date', '<>', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }else{
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 1)
                        ->where('devclothing_date', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 过滤改样
            if (isset($params['edit_sample'])){
                $spu = [];
                if($params['edit_sample']){
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 2)
                        ->where('devclothing_date', '<>', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }else{
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 2)
                        ->where('devclothing_date', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 过滤初样批版
            if (isset($params['initial_sample_batch'])){
                $spu = [];
                if($params['initial_sample']){
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 1)
                        ->where('piban_date', '<>', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }else{
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 1)
                        ->where('piban_date', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 过滤改样批版
            if (isset($params['edit_sample_batch'])){
                $spu = [];
                if($params['initial_sample']){
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 2)
                        ->where('piban_date', '<>', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }else{
                    $devclothing = DB::table('anok_devclothing')
                        ->where('version', 2)
                        ->where('piban_date', '0000-00-00 00:00:00')
                        ->where('status', 5)
                        ->select('spu')
                        ->get();
                    if ($devclothing->isNotEmpty()){
                        $spu = array_column($devclothing->toArray(), 'spu');
                    }
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 艾诺科提交
//            if(isset($params['anok_order_submit'])){
//                $spu = [];
//                if($params['anok_order_submit']){
//                    $contract_clothing = DB::table('anok_contract_clothing')
//                        ->where('status',5)
//                        ->wherenNotNull('submit_date')
//                        ->select('goods_no')
//                        ->get();
//                    if ($contract_clothing->isNotEmpty()){
//                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
//                    }
//                }else{
//                    $contract_clothing = DB::table('anok_contract_clothing')
//                        ->where('status',5)
//                        ->wherenNull('submit_date')
//                        ->select('goods_no')
//                        ->get();
//                    if ($contract_clothing->isNotEmpty()){
//                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
//                    }
//                }
//            }
            // 艾诺科审核通过
            if(isset($params['anok_order_pass'])){
                $spu = [];
                if($params['anok_order_pass']){
                    $contract_clothing = DB::table('anok_contract_clothing')
                        ->where('status',5)
                        ->whereNotNull('pass_date')
                        ->select('goods_no')
                        ->get();
                    if ($contract_clothing->isNotEmpty()){
                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
                    }
                }else{
                    $contract_clothing = DB::table('anok_contract_clothing')
                        ->where('status',5)
                        ->whereNull('pass_date')
                        ->select('goods_no')
                        ->get();
                    if ($contract_clothing->isNotEmpty()){
                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
                    }
                }
                $enquiriesModel->whereIn('spu', $spu);
            }
            // 获取spu信息
            $spuAndBaseSpuMdl = $this->spuModel::query()
                ->leftJoin('self_base_spu as sbs', 'sbs.id', '=', 'self_spu.base_spu_id')
//                ->where('sbs.is_new', 1)
                ->select('self_spu.*', 'sbs.user_id', 'sbs.base_spu', 'sbs.old_base_spu');
            // sku
            if(!empty($params['spu'])){
                $spuAndBaseSpuMdl->where(function ($query) use ($params){
                    return $query->where('self_spu.spu', 'like', '%'.$params['spu'].'%')
                        ->orWhere('self_spu.old_spu', 'like', '%'.$params['spu'].'%');
                });
            }
            // 产品开发员
            if(!empty($params['product_user_id'])){
                $spuAndBaseSpuMdl->where('sbs.user_id', $params['product_user_id']);
            }
            // 品类过滤
            if (isset($params['one_cate_id']) && !empty($params['one_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.one_cate_id', $params['one_cate_id']);
            }
            if (isset($params['two_cate_id']) && !empty($params['two_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.two_cate_id', $params['two_cate_id']);
            }
            if (isset($params['three_cate_id']) && !empty($params['three_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.three_cate_id', $params['three_cate_id']);
            }

            $spuAndBaseSpuMdl = $spuAndBaseSpuMdl->get();
            $enquiriesModel = $enquiriesModel->orderBy('offer_date', 'desc')
                ->get();
            $spulist = [];
            foreach ($enquiriesModel as $item){
                foreach ($spuAndBaseSpuMdl as $spuItem){
                    if ($item->spu == $spuItem->spu || $item->spu == $spuItem->old_spu){
                        $spulist[] = [
                            'quote_id' => $item->id,
                            'quote_type' => $item->type,
                            'spu' => $item->spu,
                            'spu_id' => $spuItem->id ?? 0,
                            'old_spu' => $spuItem->old_spu ?? '',
                            'user_id' => $spuItem->user_id ?? 0,
                            'base_id' => $spuItem->base_spu_id ?? 0,
                            'one_cate_id' => $spuItem->one_cate_id,
                            'two_cate_id' => $spuItem->two_cate_id,
                            'three_cate_id' => $spuItem->three_cate_id,
                            'content' => $spuItem->content,
                            'enquiries_date' => $item->enquiries_date,
                            'submit_date' => $item->submit_date,
                            'offer_date' => $item->offer_date,
                            'market' => $spuItem->market,
                            'memo' => $item->memo
                        ];
                    }
                }
            }
        }

        if($params['type']==2){
            //获取有下单数据得spu作为spu基础信息
            $amazonPlaceOrderTaskMdl = $this->amazonPlaceOrderTaskModel::query()
                ->leftJoin('amazon_place_order_detail as a', 'a.order_id', '=', 'amazon_place_order_task.id')
                ->where('amazon_place_order_task.type', 2)
                ->where('amazon_place_order_task.status', '>', 0);
            // 过滤计划id
            if (isset($params['place_order_task_id']) && !empty($params['place_order_task_id'])){
                $ids = explode(',', trim($params['place_order_task_id']));
                $amazonPlaceOrderTaskMdl->whereIn('amazon_place_order_task.id', $ids);
            }
            // 过滤时间段
            if (isset($params['created_at']) && !empty($params['created_at'])){
                $amazonPlaceOrderTaskMdl->whereBetween('amazon_place_order_task.ceatetime', $params['created_at']);
            }
            // 跟单人过滤
            if (isset($params['maker_id']) && !empty($params['maker_id'])){
                $anokContractClothingMdl = $this->anokContractClothingModel::query()
                    ->where('maker_id', $params['maker_id'])
                    ->select('plan_id')
                    ->get();
                $planIds = [];
                if ($anokContractClothingMdl->isNotEmpty()){
                    $planIds = array_column($anokContractClothingMdl->toArray(), 'plan_id');
                }
                $amazonPlaceOrderTaskMdl->whereIn('amazon_place_order_task.id', $planIds);
            }
            // 艾诺科审核通过
            if(isset($params['anok_order_pass'])){
                $spu = [];
                if($params['anok_order_pass']){
                    $contract_clothing = DB::table('anok_contract_clothing')
                        ->where('status',5)
                        ->whereNotNull('pass_date')
                        ->select('goods_no')
                        ->get();
                    if ($contract_clothing->isNotEmpty()){
                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
                    }
                }else{
                    $contract_clothing = DB::table('anok_contract_clothing')
                        ->where('status',5)
                        ->whereNull('pass_date')
                        ->select('goods_no')
                        ->get();
                    if ($contract_clothing->isNotEmpty()){
                        $spu = array_column($contract_clothing->toArray(), 'goods_no');
                    }
                }

                $amazonPlaceOrderTaskMdl->whereIn('a.spu', $spu);
            }
            $amazonPlaceOrderTaskMdl->orderBy('amazon_place_order_task.creattime', 'desc');
            $spulist = [];
            $amazonPlaceOrderTaskMdl = $amazonPlaceOrderTaskMdl->groupBy(['amazon_place_order_task.id', 'a.spu_id'])->get(['a.*', 'amazon_place_order_task.*']);
            // 获取spu信息
            $spuAndBaseSpuMdl = $this->spuModel::query()
                ->leftJoin('self_base_spu as sbs', 'sbs.id', '=', 'self_spu.base_spu_id')
                ->select('self_spu.*', 'sbs.user_id', 'sbs.base_spu', 'sbs.old_base_spu');
            // 过滤条件
            // sku
            if(!empty($params['spu'])){
                $spuAndBaseSpuMdl->where(function ($query) use ($params){
                    return $query->where('self_spu.spu', 'like', '%'.$params['spu'].'%')
                        ->orWhere('self_spu.old_spu', 'like', '%'.$params['spu'].'%');
                });
            }
            // 产品开发员
            if(isset($params['product_user_id']) && !empty($params['product_user_id'])){
                $spuAndBaseSpuMdl->where('sbs.user_id', $params['product_user_id']);
            }
            // 品类过滤
            if (isset($params['one_cate_id']) && !empty($params['one_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.one_cate_id', $params['one_cate_id']);
            }
            if (isset($params['two_cate_id']) && !empty($params['two_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.two_cate_id', $params['two_cate_id']);
            }
            if (isset($params['three_cate_id']) && !empty($params['three_cate_id'])){
                $spuAndBaseSpuMdl->whereIn('self_spu.three_cate_id', $params['three_cate_id']);
            }

            $spuAndBaseSpuMdl = $spuAndBaseSpuMdl->get();
            foreach ($amazonPlaceOrderTaskMdl as $item){
//                $spuArr = explode(',', $item->spulist);
                foreach ($spuAndBaseSpuMdl as $spuItem){
                    if ($item->spu == $spuItem->spu || $item->spu == $spuItem->old_spu){
                        $spulist[] = [
                            'place_order_task_id' => $item->id,
                            'place_user_id' => $item->user_id,
                            'status' => $item->status,
                            'status_name' => self::AMAZON_PLACE_ORDER_TASK_STATUS_NAME[$item->status] ?? '',
                            'spu' => $item->spu,
                            'shop_id' => $item->shop_id,
                            'created_at' => $item->creattime,
                            'spu_id' => $spuItem->id ?? 0,
                            'old_spu' => $spuItem->old_spu ?? '',
                            'user_id' => $spuItem->user_id ?? 0,
                            'base_id' => $spuItem->base_spu_id ?? 0,
                            'one_cate_id' => $spuItem->one_cate_id,
                            'two_cate_id' => $spuItem->two_cate_id,
                            'three_cate_id' => $spuItem->three_cate_id,
                            'content' => $spuItem->content,
                            'mode' => $item->mode,
                            'market' => $spuItem->market,
                            'memo' => $item->memo
                        ];
                    }
                }
            }
        }
        // 如果统计要全部数据的统计，则分页要放置最后
        $totalNum = count($spulist);
        // 数组分页
        if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])){
            $offset = $params['limit'] * ($params['page'] - 1);
            $spulist = array_slice($spulist, $offset, $params['limit']);
        }else{
            $spulist = array_slice($spulist, 0, 30); // 默认第一页，显示30条
        }

        $data = array();

        // 数据统计
        $needQuoteNum = 0; // 需求报价数量
        $quotedNum = 0; // 已报价数量

        $initialSampleGeven = 0; // 初样已给
        $initialSampleNotGeven = 0; // 初样未给

        $editSampleGeven = 0; // 改样已给
        $editSampleNotGeven = 0; // 改样未给

        $initialSampleBatchEdition = 0; // 初样已批版
        $initialSampleNotBatchEdition = 0; // 初样未批版

        $editSampleBatchEdition = 0; // 改样已批版
        $editSampleNotBatchEdition = 0; // 改样未批版

        $erpPlaceOrderApproved = 0; // ERP下单已审批
        $erpPlaceOrderNotApproved = 0; // ERP下单未审批

        $erpContractApproved = 0; // ERP合同已审批
        $erpContractNotApproved = 0; // ERP合同未审批

        $qcQualified = 0; // qc质检完成数量
        $qcUnqualified = 0; // qc质检未完成数量

        $factoryProduct = 0; // 工厂生产款数
        $factoryNotProduct = 0; // 工厂未生产款数

        $logisticsArrival = 0;  // 物流到达款数
        $logisticsNotArrival = 0; // 物流未到达款数

        $inStock = 0; // 入库完成款数
        $notInStock = 0; // 没有入库完成款数

        $outStock = 0; // 出库完成款数
        $notOutStock = 0; // 没有出库完成款数

        foreach ($spulist as $k=>$v){
            if($v['old_spu']){
                $spu = $v['old_spu'];
            }else{
                $spu = $v['spu'];
            }

            $data[$k]['img'] = $this->GetBaseSpuImg($v['base_id']);
            $nspu = preg_replace('/([\x80-\xff]*)/i','',$v['spu']);
            $data[$k]['spu'] = $spu;
            $data[$k]['enquiries'] = array();  //报价数据
            $data[$k]['devclothing'] = array();  //打样数据
            $data[$k]['contract_clothing'] = array();  //下单数据
            $data[$k]['contract_no'] = ''; //合同号
            $data[$k]['contract_report_date'] = '';
            $data[$k]['contract_create_time'] = '';
            $data[$k]['shipment_time'] = '';
            $data[$k]['in_house_time'] = '';
            $data[$k]['out_house_time'] = '';
            $data[$k]['qc_req_date'] = '';
            $data[$k]['qc_complete_date'] = '';
            $data[$k]['contract_submit'] = '';
            $data[$k]['contract_end'] = '';
            $data[$k]['order_time'] = '';
            $data[$k]['maker_name'] = ''; // 跟单员
            $data[$k]['oflow_type'] = ''; // 体系类型
            $data[$k]['supplier_code'] = ''; // 供应商编码
//            $newSpu = $this->GetNewSpu($spu);
            $data[$k]['country'] = self::COUNTRY[$v['market']] ?? ''; // 国家
            $data[$k]['product_user'] = $this->GetUsers($v['user_id'])['account'];
            $data[$k]['spu_id'] = $v['spu_id'];
            $data[$k]['memo'] = $v['memo']; // 进度备注
            $data[$k]['quote_id'] = $v['quote_id'] ?? 0; // 报价id
            $data[$k]['order_num'] = 0;

            // 品类
            //大类
            $data[$k]['one_cate_name'] = '';
            $one_cate = $this->GetCategory($v['one_cate_id']);
            if($one_cate){
                $data[$k]['one_cate_name'] = $one_cate['name'];
            }

            //二类
            $data[$k]['two_cate_name'] = '';
            $two_cate = $this->GetCategory($v['two_cate_id']);
            if($two_cate){
                $data[$k]['two_cate_name'] = $two_cate['name'];
            }

            //三类
            $data[$k]['three_cate_name'] = '';
            $three_cate = $this->GetCategory($v['three_cate_id']);
            if($three_cate){
                $data[$k]['three_cate_name'] = $three_cate['name'];
            }
            // 品名
            $data[$k]['content'] = $v['content'] ?? '';
            // 体系类别
            // 暂时放空，等后续对接修改
            $data[$k]['oflow_type'] = '';
            $data[$k]['supplier_code'] = '';

            if($params['type']==1) {
                $data[$k]['quote_id'] = $v['quote_id'];
//                //获取报价数据
//                $enquiries = DB::table('anok_enquiries')
//                    ->where('spu_id', $v['spu_id'])
//                    ->where('status', 5)
//                    ->where('type', '已报价')
//                    ->select('type', 'enquiries_date', 'offer_date')
//                    ->get();
//                if (!empty($enquiries)) {
//                    $data[$k]['enquiries'] = json_decode(json_encode($enquiries), true);
//                }
                //获取报价数据
                $data[$k]['enquiries'] = [
                    'type' => $v['quote_type'],
                    'enquiries_date' => $v['enquiries_date'],
                    'offer_date' => $v['offer_date']
                ];
                //获取打样数据
                $devclothing = DB::table('anok_devclothing')->where('spu', $spu)->where('status', 5)
                    ->select('version', 'req_date', 'devclothing_date', 'piban_date', 'req_status')
                    ->get();
                if (!$devclothing->isempty()) {
                    $data[$k]['devclothing'] = json_decode(json_encode($devclothing), true);
                }else{
                    $data[$k]['devclothing'] = [];
                }
                //获取下单数据
                $contract_clothing = DB::table('anok_contract_clothing')
                    ->where('status',5)
                    ->where('goods_no',$spu)
                    ->select('submit_date','pass_date','billno','input_userid', 'spu_id', 'maker_id', 'maker_name', 'oflow_type')
                    ->orderBy('input_date','asc')
                    ->first();
                if(!empty($contract_clothing)){
                    $data[$k]['contract_clothing'] = json_decode(json_encode($contract_clothing),true);
                    $data[$k]['input_user'] = $this->GetUsers($contract_clothing->input_userid)['account'];
                    $data[$k]['maker_name'] = $contract_clothing->maker_name; // 跟单员
                    $data[$k]['oflow_type'] = $contract_clothing->oflow_type; // 体系类型
                }

            }

            if($params['type']==2){
                //获取下单数据
                $contract_clothing = DB::table('anok_contract_clothing')
                    ->where('plan_id', 'like', '%'.$v['place_order_task_id'].'%')
                    ->where('status',5)
                    ->where('goods_no',$spu)
                    ->select('submit_date','pass_date','billno','input_userid', 'spu_id', 'maker_id', 'maker_name', 'oflow_type')
                    ->orderBy('input_date','asc')
                    ->first();
                if(!empty($contract_clothing)){
                    $data[$k]['contract_clothing'] = json_decode(json_encode($contract_clothing),true);
                    $data[$k]['input_user'] = $this->GetUsers($contract_clothing->input_userid)['account'];
                    $data[$k]['maker_name'] = $contract_clothing->maker_name; // 跟单员
                    $data[$k]['oflow_type'] = $contract_clothing->oflow_type; // 体系类型
                }

                // 获取E老板下单数据 取任务下单时间最新的一条数据
                $data[$k]['e_order_task_created_date'] = $v['created_at'];
                $data[$k]['e_order_task_id'] = $v['place_order_task_id'];
                $data[$k]['e_order_task_approved_date'] = '';
                $taskMdl = $this->taskModel::query()
                    ->leftJoin('tasks_examine as te', 'te.task_id', '=', 'tasks.Id')
                    ->where('tasks.type', 1)
                    ->where('tasks.class_id', 19)
                    ->where('tasks.ext', 'like', '%order_id='.$v['place_order_task_id'].'%')
                    ->where('te.state', 3)
                    ->select('tasks.*', 'te.time_sh')
                    ->first();
                $orderDetail = DB::table('amazon_place_order_detail')->where('order_id', $v['place_order_task_id'])->where('spu_id', $v['spu_id'])->get();
                foreach ($orderDetail as $detail){
                    $data[$k]['order_num'] += array_sum(json_decode($detail->order_num, true));
                }
                if (!empty($taskMdl)){
                    $data[$k]['e_order_task_approved_date'] = $taskMdl->time_sh;
                }
            }

            if(isset($data[$k]['contract_clothing']['billno'])){
                //获取合同交期数据
                $contract = DB::table('cloudhouse_contract')
                    ->where('exp_contractno',$data[$k]['contract_clothing']['billno'])
                    ->where('spu',$spu)
                    ->select('report_date','contract_no','create_time','create_user')
                    ->orderBy('create_time','asc')
                    ->first();
                //获取QC质检数据
                if(!empty($contract)){
                    $data[$k]['input_user'] = $this->GetUsers($contract->create_user)['account']; // 跟单人
                    $data[$k]['contract_no'] = $contract->contract_no; // 合同号
                    $data[$k]['contract_create_time'] = $contract->create_time; // ERP提交合同日期
                    $data[$k]['contract_report_date'] = $contract->report_date; // ERP工厂合同交期
                    //获取合同审批数据
                    $contract_date = DB::table('cloudhouse_contract_total')
                        ->where('contract_no',$contract->contract_no)
                        ->select('pursubmit_date','purend_date', 'supplier_short_name')
                        ->first();
                    if(!empty($contract_date)){
                        $data[$k]['contract_submit'] = $contract_date->pursubmit_date; // ERP合同审批通过日期
                        $data[$k]['contract_end'] = $contract_date->purend_date; // ERP合同审批通过日期
                        $supplierMdl = DB::table('suppliers')
                            ->where('short_name', $contract_date->supplier_short_name)
                            ->first();
                        if ($supplierMdl){
                            $data[$k]['supplier_code'] = $supplierMdl->supplier_no;
                        }
                    }
                    $qc = DB::table('anok_qc_trip')
                        ->where('goods_no',$nspu)
                        ->where('purcontract_no',$contract->contract_no)
                        ->select('req_date','complete_date','purcontract_no','idate','itype')
                        ->orderBy('req_date','asc')
                        ->first();
                    if(!empty($qc)){
                        $data[$k]['qc_req_date'] = $qc->req_date; // 提出质检需求日期
                        $data[$k]['qc_complete_date'] = $qc->complete_date; // 质检完成日期
                    }
                    //获取合同出货数据,入库数据
                    $data[$k]['contract_report_date'] = $contract->report_date; // ERP工厂合同交期
                    $shipment = DB::table('goods_transfers_detail as a')
                        ->leftJoin('goods_transfers as b','a.order_no','=','b.order_no')
                        ->where('a.contract_no',$contract->contract_no)
                        ->where('a.spu_id',$v['spu_id'])
                        ->orderBy('a.createtime','asc')
                        ->select('a.createtime','a.contract_no','a.receive_time','b.yj_arrive_time')
                        ->first();
                    if(!empty($shipment)){
                        $data[$k]['shipment_time'] = $shipment->createtime;
                        $data[$k]['in_house_time'] = $shipment->receive_time;
                        $data[$k]['logistics_arrive_time'] = $shipment->yj_arrive_time;
                    }
                    //获取出库计划数据
                    $buhuo = DB::table('amazon_buhuo_request as a')
                        ->leftJoin('amazon_buhuo_detail as b','a.id','=','b.request_id')
                        ->where('b.spu_id',$v['spu_id'])
                        ->where('a.request_status','!=',1)
                        ->select('a.request_time','b.id')
                        ->orderBy('a.request_time','asc')
                        ->first();
                    if(!empty($buhuo)){
                        $data[$k]['out_house_rq'] = $buhuo->request_time;
                        //获取出库时间
                        $request_id_json = substr(substr(json_encode(array("request_id" => "{$buhuo->id}")), 1), 0, -1);
                        $out_house = Db::table('tasks')->where('ext', 'like', "%{$request_id_json}%")->where('state','!=',2)->select('Id')->first();
                        if(!empty($out_house)){
                            $task_son = Db::table('tasks_son')->where('task_id',$out_house->Id)->where('task','审核数据，确认出库')->select('time_end_sj')->first();
                            if(!empty($task_son)){
                                $data[$k]['out_house_time'] = $task_son->time_end_sj;
                            }
                        }
                    }
                    $order = DB::table('amazon_order_item')->where('spu_id',$v['spu_id'])->select('amazon_time')->orderBy('amazon_time','asc')->first();
                    if(!empty($order)){
                        $data[$k]['order_time'] = $order->amazon_time;
                    }
                }
            }

            if (!empty($v['quote_type'])){
                // 报价统计
                if ($v['quote_type'] == '已报价'){
                    $quotedNum++;
                }elseif ($v['quote_type'] == '已提交询价'){
                    $needQuoteNum++;
                }
            }else{
                $needQuoteNum++;
                $initialSampleNotGeven++;
                $initialSampleNotBatchEdition++;
                $editSampleGeven++;
                $editSampleNotBatchEdition++;
            }

            // 打样统计
            if (!empty($data[$k]['devclothing'])){
                foreach ($data[$k]['devclothing'] as $item){
                    if ($item['version'] == 1){
                        // 初样统计
                        if ($item['devclothing_date'] != '0000-00-00 00:00:00'){ // 初样已给
                            $initialSampleGeven++;
                        }else{ // 初样未给
                            $initialSampleNotGeven++;
                        }
                        if ($item['piban_date'] != '0000-00-00 00:00:00'){ // 初样已批版
                            $initialSampleBatchEdition++;
                        }else{ // 初样未批版
                            $initialSampleNotBatchEdition++;
                        }
                    }elseif($item['version'] == 2){
                        // 改样统计
                        if ($item['devclothing_date'] != '0000-00-00 00:00:00'){ // 改样已给
                            $editSampleGeven++;
                        }else{ // 初样未给
                            $editSampleNotGeven++;
                        }
                        if ($item['piban_date'] != '0000-00-00 00:00:00'){ // 改样已批版
                            $editSampleBatchEdition++;
                        }else{ // 初样未批版
                            $editSampleNotBatchEdition++;
                        }
                    }
                }
            }else{
                $initialSampleNotGeven++;
                $initialSampleNotBatchEdition++;
                $editSampleNotGeven++;
                $editSampleNotBatchEdition++;
            }

            // ERP下单统计
            if (!empty($data[$k]['contract_clothing']['pass_date'])){
                $erpPlaceOrderApproved++;
            }else{
                $erpPlaceOrderNotApproved++;
            }
            // ERP合同审批统计
            if (!empty($data[$k]['contract_end'])){
                $erpContractApproved++;
            }else{
                $erpContractNotApproved++;
            }
            // QC质检统计
            if (!empty($data[$k]['qc_complete_date'])){
                $qcQualified++;
            }else{
                $qcUnqualified++;
            }
            // 工厂出货统计
            if (!empty($data[$k]['shipment_time'])){
                $factoryProduct++;
            }else{
                $factoryNotProduct++;
            }
            // 物流到达统计
            if (!empty($data[$k]['logistics_arrive_time'])){
                $logisticsArrival++;
            }else{
                $logisticsNotArrival++;
            }
            // 入库统计
            if (!empty($data[$k]['in_house_time'])){
                $inStock++;
            }else{
                $notInStock++;
            }
            // 出库统计
            if (!empty($data[$k]['out_house_time'])){
                $outStock++;
            }else{
                $notOutStock++;
            }
        }

//        // 如果统计要全部数据的统计，则分页要放置最后
//        $totalNum = count($data);
//        // 数组分页
//        if (isset($params['limit']) && !empty($params['limit']) && isset($params['page']) && !empty($params['page'])){
//            $offset = $params['limit'] * ($params['page'] - 1);
//            $data = array_slice($data, $offset, $params['limit']);
//        }else{
//            $data = array_slice($data, 0, 30); // 默认第一页，显示30条
//        }

        return [
            'totalNum' => $totalNum,
            'data' => $data,
//            'quote_statistics' => ['已报价款数：'.$quotedNum, '已需求款数：'.$needQuoteNum],
//            'initial_devclothing_statistics' => ['已批版款数：'.$initialDevclothing, '已需求款数：'.$initialNeedDevclothing],
//            'edit_devclothing_statistics' => ['已批版款数：'.$editDevclothing, '已需求款数：'.$editNeedDevclothing],
//            'anok_contract_statistics' => ['下单通过款数：'.$anokContractOrderNum, '未通过款数：'.$notAnokContractOrderNum],
//            'contact_statistics' => ['合同审批通过款数：'.$contractAuditNum, '未通过款数：'.$notContractAuditNum]
            'new_statistics' => [
                [
                    'title' => '报价统计',
                    'content' => ['已报价：'.$quotedNum, '未报价：'.$needQuoteNum],
                ],
                [
                    'title' => '初样样品统计',
                    'content' => ['初样已给：'.$initialSampleGeven, '初样未给：'.$initialSampleNotGeven],
                ],
                [
                    'title' => '修改样样品统计',
                    'content' => ['修改样已给：'.$editSampleGeven, '修改样未给：'.$editSampleNotGeven],
                ],
                [
                    'title' => '初样批版统计',
                    'content' => ['初样已批版：'.$initialSampleBatchEdition, '初样未批版：'.$initialSampleNotBatchEdition],
                ],
                [
                    'title' => '修改样批版统计',
                    'content' => ['修改样已批版：'.$editSampleBatchEdition, '修改样未批版：'.$editSampleNotBatchEdition],
                ],
                [
                    'title' => 'ERP下单审批统计',
                    'content' => ['已审批：'.$erpPlaceOrderApproved, '未审批：'.$erpPlaceOrderNotApproved],
                ],
                [
                    'title' => 'ERP合同审批统计',
                    'content' => ['已审批：'.$erpContractApproved, '未审批：'.$erpContractNotApproved],
                ],
                [
                    'title' => 'QC质检统计',
                    'content' => ['已质检：'.$qcQualified, '未质检：'.$qcUnqualified],
                ],
                [
                    'title' => '出货统计',
                    'content' => ['已出货：'.$factoryProduct, '未出货：'.$factoryNotProduct],
                ],
                [
                    'title' => '物流统计',
                    'content' => ['已完成：'.$logisticsArrival, '未完成：'.$logisticsNotArrival],
                ],
                [
                    'title' => '仓库入库统计',
                    'content' => ['已入库：'.$inStock, '未入库：'.$notInStock],
                ],
                [
                    'title' => '仓库出库统计',
                    'content' => ['已出库：'.$outStock, '未出库：'.$notOutStock],
                ],
            ],
            'old_statistics' => [
                [
                    'title' => 'ERP下单审批统计',
                    'content' => ['已审批：'.$erpPlaceOrderApproved, '未审批：'.$erpPlaceOrderNotApproved],
                ],
                [
                    'title' => 'ERP合同审批统计',
                    'content' => ['已审批：'.$erpContractApproved, '未审批：'.$erpContractNotApproved],
                ],
                [
                    'title' => 'QC质检统计',
                    'content' => ['已质检：'.$qcQualified, '未质检：'.$qcUnqualified],
                ],
                [
                    'title' => '出货统计',
                    'content' => ['已出货：'.$factoryProduct, '未出货：'.$factoryNotProduct],
                ],
                [
                    'title' => '物流统计',
                    'content' => ['已完成：'.$logisticsArrival, '未完成：'.$logisticsNotArrival],
                ],
                [
                    'title' => '仓库入库统计',
                    'content' => ['已入库：'.$inStock, '未入库：'.$notInStock],
                ],
                [
                    'title' => '仓库出库统计',
                    'content' => ['已出库：'.$outStock, '未出库：'.$notOutStock],
                ],
            ]
        ];
    }

     public function copyOrder($params){
        $order_id = $params['order_id'];
        $order = DB::table('amazon_place_order_task')->where('id',$order_id)->select()->first();
        if(empty($order)){
            return [
                'type' => 'fail',
                'msg' => '没有此下单数据',
            ];
        }

        $detail = DB::table('amazon_place_order_detail')->where('order_id',$order_id)->select()->get();
         if(empty($detail)){
             return [
                 'type' => 'fail',
                 'msg' => '没有此下单数据',
             ];
         }
         $order = json_decode(json_encode($order),true);
         $detail = json_decode(json_encode($detail),true);
         foreach ($detail as $k=>$v){
             $detail[$k]['unit_price'] = $v['suppliers_price'];
             $detail[$k]['num'] = json_decode($v['order_num'],true);
         }

         return [
             'type' => 'success',
             'msg' => ['order'=>$order,'detail'=>$detail],
         ];
     }

    //新增需求
     public function addDemand($params){
        $user = DB::table('users')->where('token',$params['token'])->select('Id')->first();
        if(empty($user)){
            return [
                'type' => 'fail',
                'msg' => '添加失败，未获取到用户',
            ];
        }
        $add['user_id'] = $user->Id;
        $department = DB::table('organizes_member as a')->leftJoin('organizes as b','a.organize_id','=','b.Id')->where('a.user_id',$user->Id)->select('b.name','b.Id','b.type','b.fid')->first();
         if(empty($department)){
             return [
                 'type' => 'fail',
                 'msg' => '添加失败，未获取到部门',
             ];
         }
         if($department->type==2){
             $add['department'] = $department->fid;
         }else{
             $add['department'] = $department->Id;
         }
         $add['detail'] = isset($params['detail']) ? $params['detail']: '';
         $add['title'] = isset($params['title']) ? $params['title']: '';
         $add['priority'] = isset($params['priority']) ? $params['priority']: 0;
         $add['creat_time'] = date('Y-m-d H:i:s');
         $add['progress'] = 6;

         $addData = DB::table('demand_collect')->insert($add);
         if(!$addData){
             return [
                 'type' => 'fail',
                 'msg' => '添加失败，数据库未知错误',
             ];
         }

         return [
             'type' => 'success',
             'msg' => '添加成功',
         ];
     }

     //删除需求
     public function deleteDemand($params){
         $delete = DB::table('demand_collect')->delete($params['id']);
         if($delete){
             return [
                 'type' => 'success',
                 'msg' => '删除成功',
             ];
         }else{
             return [
                 'type' => 'fail',
                 'msg' => '删除失败',
             ];
         }
     }

     //需求列表
    public function demandList($params){

        $pagenum = isset($params['page']) ? $params['page'] : 1;
        $limit = isset($params['limit']) ? $params['limit'] : 30;
        $page  =  $pagenum- 1;
        if($page!=0){
            $page  =  $page * $limit;
        }

        $data = DB::table('demand_collect');
        if(!empty($params['start_time'])){
            $data = $data->where('creat_time','>',$params['start_time']);
        }
        if(!empty($params['end_time'])){
            $data = $data->where('creat_time','<',$params['end_time']);
        }
        if(!empty($params['title'])){
            $data = $data->where('title','like','%'.$params['title'].'%');
        }
        if(!empty($params['progress'])){
            $data = $data->where('progress',$params['progress']);
        }
        if(!empty($params['department'])){
            $data = $data->where('department',$params['department']);
        }
        if(!empty($params['execute_id'])){
            $data = $data->where('execute_id','like','%'.$params['execute_id'].'%');
        }
        if(!empty($params['user_id'])){
            $data = $data->where('user_id',$params['user_id']);
        }
        if(!empty($params['priority'])){
            $data = $data->where('priority',$params['priority']);
        }

        $totalNum = $data->count();
        $data = $data
//            ->orderBy('department')
            ->orderBy('creat_time','desc')->offset($page)->limit($limit)
            ->select('id','user_id','department','title','execute_id','feedback','progress','priority','creat_time','complete_time','start_time')->get();

        $dataArr = json_decode(json_encode($data),true);
        $department = array_column($dataArr,'department');
        $department = array_unique($department);
        $departmentData = DB::table('organizes')->whereIn('Id',$department)->select('Id','name')->get();
        foreach ($departmentData as $d){
            $departmentArr[$d->Id] = $d->name;
        }

        foreach ($data as $k=>$v){
            $data[$k]->account = '';
            $userData = $this->GetUsers($v->user_id);
            if($userData){
                $data[$k]->account = $userData['account'];
            }
            $execute = explode(',',$v->execute_id);
            $data[$k]->execute_account = '';
            foreach ($execute as $e){
                $executeData =  $this->GetUsers($e);
                if($executeData){
                    $data[$k]->execute_account .= $executeData['account'].',';
                }
            }
            $data[$k]->execute_account = rtrim($data[$k]->execute_account,',');

            $data[$k]->department_name = '';
            if(isset($departmentArr[$v->department])){
                $data[$k]->department_name = $departmentArr[$v->department];
            }
//            var_dump($data[$k]->execute_account);
        }

        return [
            'data' => $data,
            'totalNum' => $totalNum,
        ];
    }

    public function demandDetail($params){
        $id = $params['id'];

        $data = DB::table('demand_collect')->where('id',$id)->select('detail')->first();

        return [
            'data' => $data->detail,
        ];
    }

    /**
     * @Desc: 获取生产下单详情报表
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/3/31 16:09
     */
    public function getPlaceOrderTaskListBySpu($params)
    {
        $list = db::table('self_spu');
        if (isset($params['spu_id'])){
            $list = $list->where('id', $params['id']);
        }

        $count = $list->count();

        if (isset($params['page']) || isset($params['limit'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offsetNum = $limit * ($page-1);
            $list = $list->limit($limit)->offset($offsetNum);
        }
        $list = $list->get();
        $orderMdl = db::table('amazon_place_order_detail as a')
            ->leftJoin('amazon_place_order_task as b', 'a.order_id', '=', 'b.id')
            ->select('a.*', 'b.status', 'b.mode', 'b.platform_id', 'b.self_type')
            ->get();
        $cateMdl = db::table('self_category')
            ->get()
            ->keyBy('Id');
        foreach ($list as $v){
            $v->img = $this->GetBaseSpuImg($v->base_spu_id) ?? '';
            $v->not_publish_task_num = 0;
            $v->published_not_audit_num = 0;
            $v->published_audit_num = 0;
            $v->contract_num = 0;
            $v->not_contract_num = 0;
            $v->not_publish_task_detail = [];
            $v->published_not_audit_detail = [];
            $v->published_audit_detail = [];
            $v->contract_detail = [];
            $v->not_contract_detail = [];
            $oneCate = $cateMdl[$v->one_cate_id]->name ?? '';
            $twoCate = $cateMdl[$v->two_cate_id]->name ?? '';
            $threeCate = $cateMdl[$v->three_cate_id]->name ?? '';
            $v->cate_name = $oneCate.'/'.$twoCate.'/'.$threeCate;
            foreach($orderMdl as $o){
                if ($o->mode == 1){
                    $o->mode_name = '集体下单';
                }elseif ($o->mode == 2){
                    $o->mode_name = '个人下单';
                }else{
                    $o->mode_name = '未定义类型';
                }
                if (is_array(json_decode($o->order_num, true))){
                    $o->order_num = array_sum(json_decode($o->order_num, true));
                    $o->not_contract_num = bcsub($o->order_num,$o->is_contracted_num);
                }

                if ($v->id != $o->spu_id){
                    continue;
                }
                if ($o->status == 4){
                    if (empty($o->is_contracted_num)){
                        $o->is_contracted_num = $o->order_num;
                    }
                    $o->not_contract_num = bcsub($o->order_num,$o->is_contracted_num);
                    $v->contract_num += $o->is_contracted_num;
                    $v->published_audit_num += $o->order_num;
                    $v->contract_detail[] = $o;
                    $v->published_audit_detail[] = $o;
                }elseif ($o->status == 0){
                    $v->not_publish_task_num += $o->order_num;
                    $v->not_contract_num += $o->not_contract_num;
                    $v->not_publish_task_detail[] = $o;
                    $v->not_contract_detail[] = $o;
                }elseif ($o->status == 1){
                    $v->published_not_audit_num += $o->order_num;
                    $v->not_contract_num += $o->not_contract_num;
                    $v->published_not_audit_detail[] = $o;
                    $v->not_contract_detail[] = $o;
                }elseif ($o->status == 2){
                    $v->published_audit_num += $o->order_num;
                    $v->not_contract_num += $o->not_contract_num;
                    $v->not_contract_detail[] = $o;
                    $v->published_audit_detail[] = $o;
                }elseif (in_array($o->status, [3,5])){
                    $v->contract_num += $o->is_contracted_num;
                    $v->published_audit_num += $o->order_num;
                    $v->not_contract_num += $o->not_contract_num;
                    $v->published_audit_detail[] = $o;
                    $v->not_contract_detail[] = $o;
                    $v->contract_detail[] = $o;
                }else{

                }
            }
        }

        return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count,'list' => $list]];
    }

    public function saveEgeingScheduleMemo($params)
    {
        try {
            $this->_checkEgeingScheduleMemoParams($params);
            DB::beginTransaction();
            // 新品时效表
            if ($params['type'] == 1){
                $update = DB::table('anok_enquiries')
                    ->where('id', $params['id'])
                    ->where('spu_id', $params['spu_id'])
                    ->update(['memo' => $params['memo']]);
            }
            // 翻单时效表
            if ($params['type'] == 2){
                $update = DB::table('amazon_place_order_detail')
                    ->where('order_id', $params['id'])
                    ->where('spu_id', $params['spu_id'])
                    ->update(['memo' => $params['memo']]);
            }
            if ($update){
                DB::commit();
                return ['code' => 200, 'msg' => '保存成功！'];
            }else{
                DB::rollback();
                return ['code' => 500, 'msg' => '保存失败，数据无变化！'];
            }
        }catch (\Exception $e){
            DB::rollback();

            return ['code' => 500, 'msg' => '保存失败！错误原因：'.$e->getMessage()];
        }
    }

    private function _checkEgeingScheduleMemoParams($params)
    {
        if (!isset($params['type']) || empty($params['type'])){
            throw new \Exception("未给定类型！");
        }else{
            if ($params['type'] == 1){
                // 新品时效表
                if (!isset($params['id']) || empty($params['id'])){
                    throw new \Exception("未给定标识！");
                }
                if (!isset($params['spu_id']) || empty($params['spu_id'])){
                    throw new \Exception("未给定spu标识！");
                }
            }else if ($params['type'] == 2){
                // 翻单时效表
                if (!isset($params['id']) || empty($params['id'])){
                    throw new \Exception("未给定标识！");
                }
                if (!isset($params['spu_id']) || empty($params['spu_id'])){
                    throw new \Exception("未给定spu标识！");
                }
            }else {
                throw new \Exception("给定类型不正确！");
            }
        }
    }

    public function saveAmazonFasinMemo($params)
    {
        try {
            // 校验参数
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('未给定标识！');
            }
            $update = DB::table('amazon_fasin')->where('id', $params['id'])->update(['memo' => $params['memo']]);

            if ($update){
                return ['code' => 200, 'msg' => '备注成功！'];
            }else{
                return ['code' => 500, 'msg' => '备注失败！'];
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '备注失败！错误原因：'.$e->getMessage()];
        }
    }

    public function saveFasinLeaveMessage($params)
    {
        try {
            // 校验参数
            if (!isset($params['fasin']) || empty($params['fasin'])){
                throw new \Exception('未给定标识！');
            }
            if (!isset($params['reviewer_id']) || empty($params['reviewer_id'])){
                throw new \Exception('未给定留言人标识！');
            }else{
                $user = $this->GetUsers($params['reviewer_id']);
                if (empty($user)){
                    throw new \Exception('未查询到点评人信息！');
                }else{
                    $params['reviewer_name'] = $user['account'];
                    $params['head_img'] = $user['heard_img'] ?? '';
                    $organizeMdl = DB::table('organizes_member as a')
                        ->leftJoin('organizes as b', 'a.organize_id', '=', 'b.Id')
                        ->where('a.user_id', $params['reviewer_id'])
                        ->first();
                    if ($organizeMdl){
                        $params['reviewer_department'] = $organizeMdl->name ?? '';
                    }else{
                        throw new \Exception('未查询到点评人所在部门信息！');
                    }
                }
            }
            if (!isset($params['user_js']) || empty($params['user_js'])){
                throw new \Exception('未给定接收人！');
            }
            if (!isset($params['content']) || empty($params['content'])){
                throw new \Exception('请输入留言内容！');
            }
            if (isset($params['fid']) && !empty($params['fid'])){
                $fasinMsg = DB::table('amazon_fasin_message')
                    ->where('id', $params['fid'])
                    ->first();
                if (empty($fasinMsg)){
                    throw new \Exception('楼主评论不存在！');
                }
                if (!isset($params['receiver_id']) || empty($params['receiver_id'])){
                    throw new \Exception('该楼主信息不存在！');
                }
                $check = db::table('amazon_fasin_message')->where('fasin', $params['fasin'])->get();
                $all =  db::table('amazon_fasin_message')->get();
                Redis::Hset('datacache:fasin_message_read', $params['fasin'], 1); // 该fasin留言全部已回复 1：是 0：否
                foreach ($check as $v){
                    $arr = true; // 默认存在未回复消息
                    foreach ($all as $_v){
                        // 判断是否有回复消息
                        if ($v->id == $_v->fid){
                            $arr = false;
                            break;
                        }
                    }
                    if ($arr){
                        Redis::Hset('datacache:fasin_message_read', $params['fasin'], 0);
                        break;
                    }
                }
            }else{
                Redis::Hset('datacache:fasin_message_read', $params['fasin'], 0);
            }
            $file = '';
            if (isset($params['file']) && !empty($params['file'])){
                $file = json_encode($params['file']);
            }
            $img = '';
            if (isset($params['img']) && !empty($params['img'])){
                $img = json_encode($params['img']);
            }
            $msgSave = [
                'reviewer_id' => $params['reviewer_id'], // 点评人id
                'content' => $params['content'], // 留言内容
                'reviewer_name' => $params['reviewer_name'],
                'reviewer_department' => $params['reviewer_department'],
                'head_img' => $params['head_img'],
                'fid' => $params['fid'] ?? 0, // 上级留言id
                'fasin' => $params['fasin'], // fasin
                'receiver_id' => $params['receiver_id'] ?? 0, // 被指定人id
                'receiver_name' => $params['receiver_name'] ?? '', // 被指定人名称
                'content_type' => $params['content_type'] ?? 1, // 留言类型 默认1：普通留言， 2：困难留言
                'is_currency' => $params['is_currency'] ?? 1, // 是否通用留言
                'created_at' => date('Y-m-d H:i:s', microtime(true)),
                'file' => $file,
                'img' => $img
            ];
            DB::beginTransaction();
            // 保存数据
            $msgId = DB::table('amazon_fasin_message')->insertGetId($msgSave);
            if ($msgId){
                // 插入消息提醒
                $title = 'fasin留言消息';
                $count = mb_strlen($params['content']) > 10 ? 10 : mb_strlen($params['content']);
                $cont = mb_substr($params['content'], 0, $count, "utf-8");
                $content = $user['account'].':'.$cont.'...';
                $userJs = array_unique($params['user_js']);
                foreach($userJs as $id){
                    $saveTiding = [
                        'user_fs' => $params['reviewer_id'],
//                    'user_fs' => 0,
                        'user_js' => $id,
                        'title' => $title,
                        'content' => $content,
                        'is_read' => 1,
                        'object_id' => $msgId,
                        'object_type' => 5,
                        'type' => 1,
                        'create_time' => date('Y-m-d H:i:s', microtime(true))
                    ];
                    $tidingId = DB::table('tidings')->insertGetId($saveTiding);

                    $task = new Task();
                    $redisTiding = $task->redis_tiding($tidingId, $params['reviewer_id'], $id, $title, $params['content'], $msgId, 5, 1);
                }

                DB::commit();

                return ['code' => 200, 'msg' => '留言成功！'];
            }else{
                DB::rollback();

                return ['code' => 500, 'msg' => '留言失败！'];
            }
        }catch (\Exception $e){
            DB::rollback();

            return ['code' => 500, 'msg' => '备注失败！错误原因：'.$e->getMessage()];
        }
    }

    public function saveFasinLeaveMessage_new($params)
    {
        try {
            // 校验参数
            if (!isset($params['fasin']) || empty($params['fasin'])){
                throw new \Exception('未给定标识！');
            }
            if (!isset($params['reviewer_id']) || empty($params['reviewer_id'])){
                throw new \Exception('未给定留言人标识！');
            }else{
                $user = $this->GetUsers($params['reviewer_id']);
                if (empty($user)){
                    throw new \Exception('未查询到点评人信息！');
                }else{
                    $params['reviewer_name'] = $user['account'];
                    $params['head_img'] = $user['heard_img'] ?? '';
                    $organizeMdl = DB::table('organizes_member as a')
                        ->leftJoin('organizes as b', 'a.organize_id', '=', 'b.Id')
                        ->where('a.user_id', $params['reviewer_id'])
                        ->first();
                    if ($organizeMdl){
                        $params['reviewer_department'] = $organizeMdl->name ?? '';
                    }else{
                        throw new \Exception('未查询到点评人所在部门信息！');
                    }
                }
            }
            if (!isset($params['user_js']) || empty($params['user_js'])){
                throw new \Exception('未给定接收人！');
            }
            if (!isset($params['content']) || empty($params['content'])){
                throw new \Exception('请输入留言内容！');
            }
            if (isset($params['fid']) && !empty($params['fid'])){
                $fasinMsg = DB::table('amazon_fasin_message')
                    ->where('id', $params['fid'])
                    ->first();
                if (empty($fasinMsg)){
                    throw new \Exception('楼主评论不存在！');
                }
                if (!isset($params['receiver_id']) || empty($params['receiver_id'])){
                    throw new \Exception('该楼主信息不存在！');
                }
                $check = db::table('amazon_fasin_message')->where('faisn', $params['fasin'])->get();
                $all =  db::table('amazon_fasin_message')->get();
                Redis::Hset('datacache:fasin_message_read', $params['fasin'], 1); // 该fasin留言全部已回复 1：是 0：否
                foreach ($check as $v){
                    $arr = true; // 默认存在未回复消息
                    foreach ($all as $_v){
                        // 判断是否有回复消息
                        if ($v->id == $_v->fid){
                            $arr = false;
                            break;
                        }
                    }
                    if ($arr){
                        Redis::Hset('datacache:fasin_message_read', $params['fasin'], 0);
                        break;
                    }
                }
            }else{
                Redis::Hset('datacache:fasin_message_read', $params['fasin'], 0);
            }
            $file = '';
            if (isset($params['file']) && !empty($params['file'])){
                $file = json_encode($params['file']);
            }
            $img = '';
            if (isset($params['img']) && !empty($params['img'])){
                $img = json_encode($params['img']);
            }
            if (!isset($params['fasin_code']) || empty($params['fasin_code'])){
                $fasinCode = $this->GetFasinCodeNew($params);
                if (empty($fasinCode)){
                    throw new \Exception($params['fasin'].'未绑定链接代号！');
                }
                $params['fasin_code'] = array_column($fasinCode, 'fasin_code');
            }
            DB::beginTransaction();

            foreach ($params['fasin_code'] as $fasinCode){
                $msgSave = [
                    'reviewer_id' => $params['reviewer_id'], // 点评人id
                    'content' => $params['content'], // 留言内容
                    'reviewer_name' => $params['reviewer_name'],
                    'reviewer_department' => $params['reviewer_department'],
                    'head_img' => $params['head_img'],
                    'fid' => $params['fid'] ?? 0, // 上级留言id
                    'fasin' => $params['fasin'], // fasin
                    'receiver_id' => $params['receiver_id'] ?? 0, // 被指定人id
                    'receiver_name' => $params['receiver_name'] ?? '', // 被指定人名称
                    'content_type' => $params['content_type'] ?? 1, // 留言类型 默认1：普通留言， 2：困难留言
                    'is_currency' => $params['is_currency'] ?? 1, // 是否通用留言
                    'created_at' => date('Y-m-d H:i:s', microtime(true)),
                    'file' => $file,
                    'img' => $img,
                    'fasin_code' => $fasinCode,
                ];
                // 保存数据
                $msgId = DB::table('amazon_fasin_message')->insertGetId($msgSave);

                if ($msgId){
                    // 插入消息提醒
                    $title = 'fasin留言消息';
                    $count = mb_strlen($params['content']) > 10 ? 10 : mb_strlen($params['content']);
                    $cont = mb_substr($params['content'], 0, $count, "utf-8");
                    $content = $user['account'].':'.$cont.'...';
                    $userJs = array_unique($params['user_js']);
                    foreach($userJs as $id){
                        $saveTiding = [
                            'user_fs' => $params['reviewer_id'],
//                    'user_fs' => 0,
                            'user_js' => $id,
                            'title' => $title,
                            'content' => $content,
                            'is_read' => 1,
                            'object_id' => $msgId,
                            'object_type' => 5,
                            'type' => 1,
                            'create_time' => date('Y-m-d H:i:s', microtime(true))
                        ];
                        $tidingId = DB::table('tidings')->insertGetId($saveTiding);

                        $task = new Task();
                        $redisTiding = $task->redis_tiding($tidingId, $params['reviewer_id'], $id, $title, $params['content'], $msgId, 5, 1);
                    }

                    DB::commit();

                    return ['code' => 200, 'msg' => '留言成功！'];
                }else{
                    DB::rollback();

                    return ['code' => 500, 'msg' => '留言失败！'];
                }
            }


        }catch (\Exception $e){
            DB::rollback();

            return ['code' => 500, 'msg' => '备注失败！错误原因：'.$e->getMessage()];
        }
    }

    public function getAmazonFasinMemoList($params)
    {
        try {
            $fasinMessageMdl = DB::table('amazon_fasin_message');
            if (!isset($params['is_all']) || empty($params['is_all'])){
                if (!isset($params['fasin']) || empty($params['fasin'])){
                    throw new \Exception('请传入Fasin!');
                }
                $fasinMessageMdl = $fasinMessageMdl->where('fid', 0);
            }

            if (isset($params['one_cate_id']) || isset($params['two_cate_id']) || isset($params['three_cate_id'])){
                $fasin = Db::table('amazon_fasin');
                if(isset($params['one_cate_id'])){
                    $fasin = $fasin->whereIn('one_cate_id',$params['one_cate_id']);
                }
                if(isset($params['two_cate_id'])){
                    $fasin = $fasin->whereIn('two_cate_id',$params['two_cate_id']);
                }
                if(isset($params['three_cate_id'])){
                    $fasin = $fasin->whereIn('three_cate_id',$params['three_cate_id']);
                }
                $fasin = $fasin->get();
                $fasinArr = [];
                if ($fasin->isNotEmpty()){
                    $fasin = json_decode(json_encode($fasin), true);
                    $fasinArr = array_column($fasin, 'fasin');
                }
                if (!empty($fasinArr)){
                    $fasinMessageMdl = $fasinMessageMdl->whereIn('fasin', $fasinArr);
                }
            }

            if (isset($params['fasin']) && !empty($params['fasin'])){
                $fasins = explode(',', $params['fasin']);
                $fasinMessageMdl = $fasinMessageMdl->where(function($q) use ($fasins){
                    foreach ($fasins as $fasin){
                        $q->orWhere('fasin', 'like', '%'.$fasin.'%');
                    }
                    return $q;
                });
            }

            // 点评人
            if (isset($params['reviewer_id']) && !empty($params['reviewer_id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('reviewer_id', $params['reviewer_id']);
            }
            if (isset($params['id']) && !empty($params['id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('id', $params['id']);
            }
            if (isset($params['receiver_id']) && !empty($params['receiver_id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('receiver_id', $params['receiver_id']);
            }
            // 留言类型
            if (isset($params['content_type']) && !empty($params['content_type'])){
                $fasinMessageMdl = $fasinMessageMdl->where('content_type', $params['content_type']);
            }
            // 是否通用
            if (isset($params['is_currency']) && !empty($params['is_currency'])){
                $fasinMessageMdl = $fasinMessageMdl->where('is_currency', $params['is_currency']);
            }
            // 创建时间
            if (isset($params['created_at']) && !empty($params['created_at'])){
                $fasinMessageMdl = $fasinMessageMdl->whereBetween('created_at', $params['created_at']);
            }
            $count = $fasinMessageMdl->count();

            if (!isset($params['is_all']) || empty($params['is_all'])){
                $limit = $params['limit'] ?? 30;
                $page = $params['page'] ?? 1;
                $offset = $limit * ($page-1);
                $fasinMessageMdl = $fasinMessageMdl->orderBy('created_at', 'DESC')->limit($limit)
                    ->offset($offset);
            }else{
                $limit = $params['limit'] ?? 30;
                $page = $params['page'] ?? 1;
                $offset = $limit * ($page-1);
                $fasinMessageMdl = $fasinMessageMdl->orderBy('reviewer_id', 'ASC')->orderBy('created_at', 'DESC')->limit($limit)
                    ->offset($offset);
            }
            $fasinMessageMdl = $fasinMessageMdl->get();
//            if ($fasinMessageMdl){
//                $fasinMessageMdl = $fasinMessageMdl->toArray();
//            }else{
//                $fasinMessageMdl = [];
//            }


//            if ($msgMdl){
//                $msgMdl = $msgMdl->toArray();
//            }else{
//                $msgMdl = [];
//            }
//            foreach ($fasinMessageMdl as &$item){
//                $child = [];
//                foreach ($msgMdl as $msg){
//                    if ($item['id'] == $msg['fid']){
//                        $child[] = $msg;
//                    }
//                }
//                $item['child'] = $child;
//            }
//            if (!isset($params['is_all']) || empty($params['is_all'])){
                $msgMdl = DB::table('amazon_fasin_message')
                    ->where('fid', '<>', 0);
                if (!isset($params['is_all']) || empty($params['is_all'])){
                    $msgMdl = $msgMdl->where('fasin', $params['fasin']);
                }
                $msgMdl = $msgMdl->orderBy('created_at', 'ASC')
                    ->get();
                $fasinCodeMdl = db::table('amazon_fasin_bind as a')
                    ->leftJoin('shop as b', 'a.shop_id', '=', 'b.Id')
                    ->get(['a.*', 'b.country_id'])
                    ->keyBy('fasin_code');
                foreach ($fasinMessageMdl as $item){
                    $child = [];
                    foreach ($msgMdl as $msg){
                        if ($item->id == $msg->fid){
                            $msg->content_type_name = Constant::FASIN_CONTENT_TYPE[$msg->content_type] ?? '';
                            $msg->is_currency_name = $msg->is_currency ? '通用型' : '一次性型';
                            $msg->file = json_decode($msg->file, true);
                            $msg->img = json_decode($msg->img, true);
//                            $msg->content = strip_tags($msg->content, '<br> <p> <a>');
                            $child[] = $msg;
                        }
                    }
                    $item->child = $child;
                    $item->content_type_name = Constant::FASIN_CONTENT_TYPE[$item->content_type] ?? '';
                    $item->is_currency_name = $item->is_currency ? '通用型' : '一次性型';
                    $item->file = json_decode($item->file, true);
                    $item->img = json_decode($item->img, true);
                    $fasinCode = $this->GetFasinCodeNew($item->fasin);
                    $fasinCode = array_column($fasinCode, 'fasin_code');
                    $item->fasin_code = $fasinCode;
                    $country_id = [];
                    foreach ($fasinCode as $fc){
                        $country_id[] = $fasinCodeMdl[$fc]->country_id ?? 0;
                    }
                    $item->country_id = $country_id;
//                    $item->content = strip_tags($item->content, '<br> <p> <a>');
                }
//            }else{
//                $fasinBind = DB::table('amazon_fasin as a')
//                    ->leftJoin('amazon_fasin_bind as b', 'a.fasin', '=', 'b.fasin')
//                    ->leftJoin('shop as c', 'b.shop_id', '=', 'c.Id')
//                    ->get(['a.fasin', 'b.fasin_code', 'b.shop_id', 'c.shop_name', 'c.country_id']);
//                foreach ($fasinMessageMdl as $item) {
//                    $fasinCode = [];
//                    foreach ($fasinBind as $bind){
//                        if ($item->fasin == $bind->fasin){
//                            $item->country_id = $bind->country_id;
//                            $fasinCode[] = $bind->fasin_code;
//                        }
//                    }
//                    $item->content_type_name = Constant::FASIN_CONTENT_TYPE[$item->content_type] ?? '';
//                    $item->is_currency_name = $item->is_currency ? '通用型' : '一次性型';
//                    $item->file = json_decode($item->file, true);
//                    $item->img = json_decode($item->img, true);
//                    $item->fasin_code = $fasinCode;
////                    $item->content = strip_tags($item->content, '<br> <p> <a>');
//                }
//            }


            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $fasinMessageMdl]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！错误原因：'.$e->getMessage()];
        }
    }

    public function getAmazonFasinMemoList_new($params)
    {
        try {
            $fasinMessageMdl = DB::table('amazon_fasin_message');
            if (!isset($params['is_all']) || empty($params['is_all'])){
                if (!isset($params['fasin']) || empty($params['fasin'])){
                    throw new \Exception('请传入Fasin!');
                }
                $fasinMessageMdl = $fasinMessageMdl->where('fid', 0);
            }

            if (isset($params['one_cate_id']) || isset($params['two_cate_id']) || isset($params['three_cate_id'])){
                $fasin = Db::table('amazon_fasin');
                if(isset($params['one_cate_id'])){
                    $fasin = $fasin->whereIn('one_cate_id',$params['one_cate_id']);
                }
                if(isset($params['two_cate_id'])){
                    $fasin = $fasin->whereIn('two_cate_id',$params['two_cate_id']);
                }
                if(isset($params['three_cate_id'])){
                    $fasin = $fasin->whereIn('three_cate_id',$params['three_cate_id']);
                }
                $fasin = $fasin->get();
                $fasinArr = [];
                if ($fasin->isNotEmpty()){
                    $fasin = json_decode(json_encode($fasin), true);
                    $fasinArr = array_column($fasin, 'fasin');
                }
                if (!empty($fasinArr)){
                    $fasinMessageMdl = $fasinMessageMdl->whereIn('fasin', $fasinArr);
                }
            }

            if (isset($params['fasin']) && !empty($params['fasin'])){
                $fasins = explode(',', $params['fasin']);
                $fasinMessageMdl = $fasinMessageMdl->where(function($q) use ($fasins){
                    foreach ($fasins as $fasin){
                        $q->orWhere('fasin', 'like', '%'.$fasin.'%');
                    }
                    return $q;
                });
            }

            if (isset($params['fasin_code']) && !empty($params['fasin_code'])){
                $fasinCodes = explode(',', $params['fasin_code']);
                $fasinMessageMdl = $fasinMessageMdl->where(function($q) use ($fasinCodes){
                    foreach ($fasinCodes as $fasinCode){
                        $q->orWhere('fasin_code', 'like', '%'.$fasinCode.'%');
                    }
                    return $q;
                });
            }

            // 点评人
            if (isset($params['reviewer_id']) && !empty($params['reviewer_id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('reviewer_id', $params['reviewer_id']);
            }
            if (isset($params['id']) && !empty($params['id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('id', $params['id']);
            }
            if (isset($params['receiver_id']) && !empty($params['receiver_id'])){
                $fasinMessageMdl = $fasinMessageMdl->where('receiver_id', $params['receiver_id']);
            }
            // 留言类型
            if (isset($params['content_type']) && !empty($params['content_type'])){
                $fasinMessageMdl = $fasinMessageMdl->where('content_type', $params['content_type']);
            }
            // 是否通用
            if (isset($params['is_currency']) && !empty($params['is_currency'])){
                $fasinMessageMdl = $fasinMessageMdl->where('is_currency', $params['is_currency']);
            }
            // 创建时间
            if (isset($params['created_at']) && !empty($params['created_at'])){
                $fasinMessageMdl = $fasinMessageMdl->whereBetween('created_at', $params['created_at']);
            }
            $count = $fasinMessageMdl->count();

            if (!isset($params['is_all']) || empty($params['is_all'])){
                $limit = $params['limit'] ?? 30;
                $page = $params['page'] ?? 1;
                $offset = $limit * ($page-1);
                $fasinMessageMdl = $fasinMessageMdl->orderBy('created_at', 'DESC')->limit($limit)
                    ->offset($offset);
            }else{
                $fasinMessageMdl = $fasinMessageMdl->orderBy('reviewer_id', 'ASC')->orderBy('created_at', 'DESC');
            }
            $fasinMessageMdl = $fasinMessageMdl->get();
//            if ($fasinMessageMdl){
//                $fasinMessageMdl = $fasinMessageMdl->toArray();
//            }else{
//                $fasinMessageMdl = [];
//            }


//            if ($msgMdl){
//                $msgMdl = $msgMdl->toArray();
//            }else{
//                $msgMdl = [];
//            }
//            foreach ($fasinMessageMdl as &$item){
//                $child = [];
//                foreach ($msgMdl as $msg){
//                    if ($item['id'] == $msg['fid']){
//                        $child[] = $msg;
//                    }
//                }
//                $item['child'] = $child;
//            }
            if (!isset($params['is_all']) || empty($params['is_all'])){
                $msgMdl = DB::table('amazon_fasin_message')
                    ->where('fasin', $params['fasin'])
                    ->where('fid', '<>', 0)
                    ->orderBy('created_at', 'ASC')
                    ->get();
                foreach ($fasinMessageMdl as $item){
                    $child = [];
                    foreach ($msgMdl as $msg){
                        if ($item->id == $msg->fid){
                            $msg->content_type_name = Constant::FASIN_CONTENT_TYPE[$msg->content_type] ?? '';
                            $msg->is_currency_name = $msg->is_currency ? '通用型' : '一次性型';
                            $msg->file = json_decode($msg->file, true);
                            $msg->img = json_decode($msg->img, true);
                            $child[] = $msg;
                        }
                    }
                    $item->child = $child;
                    $item->content_type_name = Constant::FASIN_CONTENT_TYPE[$item->content_type] ?? '';
                    $item->is_currency_name = $item->is_currency ? '通用型' : '一次性型';
                    $item->file = json_decode($item->file, true);
                    $item->img = json_decode($item->img, true);
                }
            }else{
                $fasinBind = DB::table('amazon_fasin as a')
                    ->leftJoin('amazon_fasin_bind as b', 'a.fasin', '=', 'b.fasin')
                    ->leftJoin('shop as c', 'b.shop_id', '=', 'c.Id')
                    ->get(['a.fasin', 'b.fasin_code', 'b.shop_id', 'c.shop_name', 'c.country_id']);
                foreach ($fasinMessageMdl as $item) {
                    $fasinCode = [];
                    foreach ($fasinBind as $bind){
                        if ($item->fasin == $bind->fasin){
                            $item->country_id = $bind->country_id;
                            $fasinCode[] = $bind->fasin_code;
                        }
                    }
                    $item->content_type_name = Constant::FASIN_CONTENT_TYPE[$item->content_type] ?? '';
                    $item->is_currency_name = $item->is_currency ? '通用型' : '一次性型';
                    $item->file = json_decode($item->file, true);
                    $item->img = json_decode($item->img, true);
                    $item->fasin_code = $fasinCode;
                }
            }


            return ['code' => 200, 'msg' => '获取成功！', 'data' => ['count' => $count, 'list' => $fasinMessageMdl]];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '获取失败！错误原因：'.$e->getMessage()];
        }
    }

    /**
     * @Desc:删除留言
     * @param $params
     * @return array
     * @author: Liu Sinian
     * @Time: 2023/5/10 16:00
     */
    public function deleteAmazonFasinLeaveMessage($params)
    {
        try{
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('请给定删除标识！');
            }
            if (!isset($params['reviewer_id']) || empty($params['reviewer_id'])){
                throw new \Exception('请给定操作人标识！');
            }
            $msgMdl = DB::table('amazon_fasin_message')->where('id', $params['id'])->first();
            if (empty($msgMdl)){
                throw new \Exception('该留言不存在或已被删除！');
            }
            if ($params['reviewer_id'] != $msgMdl->reviewer_id){
                throw new \Exception('不可删除他人留言！');
            }
            $delete = DB::table('amazon_fasin_message')->where('id', $params['id'])->delete();
            if ($msgMdl->fid == 0){
                DB::table('amazon_fasin_message')->where('fid', $params['id'])->delete();
            }
            if ($delete){
                return ['code' => 200, 'msg' => '删除成功！'];
            }else{
                return ['code' => 500, 'msg' => '删除失败！'];
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '删除失败！错误原因：'.$e->getMessage().'； '.$e->getLine()];
        }
    }

    public function thumbsUpAmazonFasinLeaveMessage($params)
    {
        try{
            if (!isset($params['id']) || empty($params['id'])){
                throw new \Exception('请给定删除标识！');
            }
            $msgMdl = DB::table('amazon_fasin_message')->where('id', $params['id'])->first();
            if (empty($msgMdl)){
                throw new \Exception('该留言不存在或已被删除！');
            }
            $likesNum = $msgMdl->likes_num+1;
            DB::table('amazon_fasin_message')->where('id', $params['id'])->update(['likes_num' => $likesNum]);

            return ['code' => 200, 'msg' => '点赞成功！'];
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '点赞失败！错误原因：'.$e->getMessage().'； '.$e->getLine()];
        }
    }

    public function saveFasinCodeCoreWord($params)
    {
        try {
            if (!isset($params['fasin_code']) || empty($params['fasin_code'])){
                throw new \Exception('未给定链接代号');
            }
            $fasinCode = db::table('amazon_fasin_bind')->where('fasin_code', $params['fasin_code'])->first();
            if (empty($fasinCode)){
                throw new \Exception('未查询到该链接代号！');
            }
            $update = db::table('amazon_fasin_bind')->where('fasin_code', $params['fasin_code'])->update(['core_word' => $params['core_word'] ?? '', 'strategy' => $params['strategy'] ?? '']);
            if ($update){
                return ['code' => 200, 'msg' => '编辑成功！'];
            }else{
                throw new \Exception('无数据变化！');
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '编辑失败！原因：'.$e->getMessage().'; 位置：'.$e->getLine()];
        }
    }

    public function saveFasinSituation($params)
    {
        try {
            if (!isset($params['fasin_code']) || empty($params['fasin_code'])){
                throw new \Exception('未给定链接代号');
            }
            $fasinCode = db::table('amazon_fasin_bind')->where('fasin_code', $params['fasin_code'])->first();
            if (empty($fasinCode)){
                throw new \Exception('未查询到该链接代号！');
            }
            $update = db::table('amazon_fasin_bind')->where('fasin_code', $params['fasin_code'])->update(['situation' => $params['situation'] ?? 0]);
            if ($update){
                return ['code' => 200, 'msg' => '编辑成功！'];
            }else{
                throw new \Exception('无数据变化！');
            }
        }catch (\Exception $e){
            return ['code' => 500, 'msg' => '编辑失败！原因：'.$e->getMessage().'; 位置：'.$e->getLine()];
        }
    }

    public function getFasinCodeList($params)
    {
        $fasinCodeMdl = db::table('amazon_fasin_bind');
        if (isset($params['fasin']) && !empty($params['fasin'])){
            $fasinCodeMdl = $fasinCodeMdl->where('fasin', 'like', '%'.$params['fasin'].'%');
        }

        $count = $fasinCodeMdl->count();

        if (isset($params['limit']) || isset($params['page'])){
            $limit = $params['limit'] ?? 30;
            $page = $params['page'] ?? 1;
            $offset = $limit * ($page-1);
            $fasinCodeMdl = $fasinCodeMdl->limit($limit)->offset($offset);
        }

        $fasinCodeMdl = $fasinCodeMdl->get();

        return ['code'=>200, 'msg' => '获取成功!', 'data' => ['count' => $count, 'list' => $fasinCodeMdl]];
    }

    public function GetAdjustInventoryList($params)
    {
        $pagenum  = isset($params['page']) ? $params['page'] : 1;
        $limit    = isset($params['limit']) ? $params['limit'] : 30;

        $page = $pagenum - 1;
        if ($page != 0) {
            $page = $page * $limit;
        }

        $query = DB::table('adjust_inventory_log');

        if (isset($params['start_time']) && isset($params['end_time'])) {
            $startTime = $params['start_time'];
            $endTime   = $params['end_time'];
            $query->whereBetween('day', [$startTime, $endTime]);
        }

        if (isset($params['warehouse_id'])) {
            $query->where('warehouse_id', $params['warehouse_id']);
        }

        if (isset($params['location_id'])) {
            $query->where('location_id', $params['location_id']);
        }

        if (isset($params['receive_platform_id'])) {
            $query->where('receive_platform_id', $params['receive_platform_id']);
        }

        if (isset($params['user_id'])) {
            $query->where('user_id', $params['user_id']);
        }

        if (isset($params['custom_sku'])) {
            $customSkuIds = db::table('self_custom_sku')
                ->where('custom_sku', 'like', '%' . $params['custom_sku'] . '%')
                ->orWhere('old_custom_sku', 'like', '%' . $params['custom_sku'] . '%')
                ->pluck('id');

            if ($customSkuIds->isEmpty()) {
                return ['code' => 200, 'msg' => '获取成功!', 'data' => ['total_num' => 0, 'data' => []]];
            }

            $query->whereIn('custom_sku_id', $customSkuIds);
        }

        $totalNum = $query->count();

        if ($totalNum == 0) {
            return ['code'=>200, 'msg' => '获取成功!', 'data' => ['total_num' => 0, 'data' => []]];
        }

        $list = $query->orderBy('id', 'desc')->offset($page)->limit($limit)->get();

        foreach ($list as $k => $v) {
            $warehouseInfo     = $this->GetWarehouse($v->warehouse_id);
            $v->warehouse_name = $warehouseInfo ? $warehouseInfo['warehouse_name'] : '';

            $locationInfo     = $this->Getlocation($v->location_id);
            $v->location_name = $locationInfo ? $locationInfo['location_name'] : '';

            $platformInfo     = $this->GetPlatform($v->platform_id);
            $v->platform_name = $platformInfo ? $platformInfo['name'] : '';

            $receivePlatformInfo      = $this->GetPlatform($v->receive_platform_id);
            $v->receive_platform_name = $receivePlatformInfo ? $receivePlatformInfo['name'] : '';

            $userInfo     = $this->GetUsers($v->user_id);
            $v->user_name = $userInfo ? $userInfo['account'] : '';
        }

        $data['total_num'] = $totalNum;
        $data['data']      = $list;
        return ['code'=>200, 'msg' => '获取成功!', 'data' => $data];
    }

}